我不敢问,因为关于这个主题还有很多其他帖子(例如一个和两个),但这些帖子中的解决方案似乎都不适用于我.
我试图将一个JSON编码的对象从页面传递给PHP控制器,然后回复一些信息.
如果我在Firebug中观看,我可以看到在"Post"选项卡下发送的对象,但是当我打印出$ _GET,$ _POST和$ _REQUEST数组时,我看不到任何关于json对象的内容.$ _GET数组至少显示我的'update-player'查询字符串,但POST是空的,REQUEST只显示我有的一些本地cookie.
这是我的jQuery代码.正如您所看到的,我现在正在硬编码JSON,目的是我将使用jQuery方法更新本地对象.
function sendPlayerUpdate(row, col) {
var playerinfo = [
{
"id": 1,
"row": row,
"col": col
}
];
alert(playerinfo[0].id); //debugging
$.ajax({
type: 'POST',
url:"controller.php?a=update-player",
//data: $.toJSON(playerinfo[0],
data: { json: JSON.stringify(playerinfo) },
contentType: "application/json",
success: function (){
},
dataType: 'json'
});
};
Run Code Online (Sandbox Code Playgroud)
我处理请求的相应PHP代码:
// update player information from AJAX POST
case "update-player":
if (isset($_POST['json'])) echo "json received\n\n";
else echo "json not received\n\n";
echo "GET VARIABLES\n";
print_r($_GET);
echo "\n\nPOST VARIABLES\n";
print_r($_POST);
echo "\n\nREQUEST VARIABLES\n";
print_r($_REQUEST);
Run Code Online (Sandbox Code Playgroud)
而且,我在Firebug中看到的:
json没收到
GET VARIABLES
Array
(
[a] => update-player
)
POST VARIABLES
Array
(
)
REQUEST VARIABLES
Array
(
[a] => update-player
(local cookies)
)
Run Code Online (Sandbox Code Playgroud)
尝试PHP如下(当请求是一个应用程序/ json,那么你将不会获得数据到$ _POST)
var_dump(json_decode(file_get_contents("php://input")));
Run Code Online (Sandbox Code Playgroud)