我想要使用POST方法发送一个JSON对象。
问题:我该如何在服务器端的PHP中读取对象?发送的JSON的关键是什么?
什么是问题?
编辑后:
我修改了我的代码为:
var user = {
"first_name": first_name.value,
"last_name": last_name.value,
"age": age.value,
"email": email.value
};
这是我发送对象的方式:
var request;
var url = 'ajax_serverside_JSON.php';
var destination;
function ajax_call(src, jsonObj, dst, method) {
this.src = src;
destination = dst;
this.objJSON = jsonObj;
this.request = getXMLHttpRequest();
this.request.onreadystatechange = getResponse;
if (method == 'POST') {
sendPostRequest(objJSON);
}
return;
}
function sendPostRequest(objJSON) {
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.send(JSON.stringify(objJSON));
return;
}
function getXMLHttpRequest() {
try {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera,Safari
request = new XMLHttpRequest();
} else {
// code for IE6, IE5
request = new ActiveXObject("Microsoft.XMLHTTP");
}
} catch (e) {
alert('The browser doesn\'t support AJAX: ' + e);
request = false;
}
return request;
}
function getResponse() {
if (request.readyState == 4 && request.status == 200) {
document.getElementById(destination).innerHTML += request.response;
}
}
问题:我该如何在服务器端的PHP中读取对象?发送的JSON的关键是什么?
echo var_dump($_POST)
将显示以下内容: array (size=0)
empty
什么是问题?
编辑后:
我修改了我的代码为:
this.objJSON = jsonObj;
并且
request.send("user=" + JSON.stringify(this.objJSON));
我试着阅读JSON对象:
<?php
if (isset ( $_POST ['user'] )) {
$obj = json_decode ( $_POST ['user'] );
echo "isset";
} else {
echo "is not set ";
echo var_dump ( $_POST );
}
?>
...还是同样的问题:
is not set
array (size=0)
empty
request.send('data=' + encodeURIComponent(JSON.stringify(this.objJSON)));
不起作用... 它给了我Undefined index: data
,就像之前一样。 - Iulian RoscasetRequestHeader
调用给删掉了吗? - Barmar