【发布时间】:2014-02-07 20:24:30
【问题描述】:
我想用 POST 发送一个 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 obj:
<?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
【问题讨论】:
标签: javascript ajax json xmlhttprequest