将JSON传递给PHP

Passing JSON to PHP

本文关键字:PHP JSON      更新时间:2023-09-26

这是我在javascript中的函数:

function callRemoteService(requestId, sObjectId, bObjectId) {
$.ajax({
    url: "../../../serviceRemoteEngine.php",
    dataType: "json",
    contentType: "application/json",
    type: "POST",
    timeout: 1000,
    data: JSON.stringify({"requestId":requestId,"SOobjectId":sObjectId,"SBobjectId":bObjectId}),
    success: function(remoteResponse){
        alert(remoteResponse.msg);
    }
});
}

这是serviceRemoteEngine.php

echo json_encode(array("msg" => $_POST["SOobjectId"]));

函数通过以下参数调用:

callRemoteService('remove', 15, 0)

问题是,在警报消息中显示的不是15,而是null

但是,当我将PHP文件改为:

echo json_encode(array("msg" => "message"));

"message"文本显示为js alert.

为什么?

发送ajax请求时不需要调用JSON.stringify(),因为$.ajax()函数期望参数的关联数组,而不是字符串。

function callRemoteService(requestId, sObjectId, bObjectId) {
    $.ajax({
        url: "../../../serviceRemoteEngine.php",
        dataType: "json",
        contentType: "application/json",
        type: "POST",
        timeout: 1000,
        data: {"requestId":requestId,"SOobjectId":sObjectId,"SBobjectId":bObjectId},
        success: function(remoteResponse){
            alert(remoteResponse.msg);
        }
    });
}

PHP期望post/get请求具有key=value对。你发送的是一个空字符串,所以就是value。由于没有键,PHP不能(也不会)将任何东西放入$_POST中,因为没有键来附加value

data: {foo: JSON.stringify(...)}

echo $_POST['foo']

你的PHP的JSON是这样的:

echo json_encode(array("msg" => "message"));

但是你应该看看添加适当的JSON头是否有助于澄清问题。这样的:

$json_data = json_encode(array("msg" => "message"));
header('X-JSON: (' . $json_data . ')');
header('Content-type: application/x-json');
echo $json_data;

另外,再次阅读您的问题,您似乎想立即获得$_POST["SOobjectId"] &然后通过JSON发送回来?你确定$_POST包含任何东西吗?在PHP文件中,在执行其他操作之前,执行以下操作:

echo '<pre>';
print_r($_POST);
echo '</pre>';

或者为$_REQUEST执行以下操作以查看数据是否传输:

echo '<pre>';
print_r($_REQUEST);
echo '</pre>'; 

也许您需要在PHP文件中这样做。通过file_get_contents('php://input')获取原始$_POST数据,然后解码并以这种方式处理。我所有的修改——包括这个想法——都在下面:

$json_decoded_array = json_decode(file_get_contents('php://input'), true);
$json_data = json_encode(array("msg" => $json_decoded_array['SOobjectId']));
header('X-JSON: (' . $json_data . ')');
header('Content-type: application/x-json');
echo $json_data;