0

我正在使用 Ajax 向我的 php 文件发送 HTTP POST 请求,但没有得到想要的结果。$_POST 和 $_GET 都是空的。我想我忽略了一些东西,但我不知道是什么。

这是我触发请求的代码:

this.save = function() {

    alert(ko.toJSON([this.name, this.description, this.pages]));
    $.ajax("x", {
        data: ko.toJSON([this.name, this.description, this.pages]),
        type: "post", contentType: "application/json",
        success: function(result) { alert(result) },
        error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
    });
};

请注意,我在第 3 行警告 JSON。该 JSON 是正确的,因此第 5 行的输入是有效的。

我在 PHP 中的测试方法:

header('Content-type: application/json; charset=utf-8');
echo json_encode(array_merge($_POST, $_GET));
exit;

我得到的响应是一个空数组。

  • 我测试了输入(见上文);
  • 我知道 Ajax 调用本身会成功,如果我将 PHP 示例中的第二行替换json_encode(array('success' => true));为我的页面中的第二行 - 所以 URL 是正确的。
  • 我用 GET 和 POST 测试了它,得到了类似的负面结果。
4

1 回答 1

2

您正在发送 JSON 请求,这就是 $_POST 和 $_GET 都为空的原因。尝试像这样发送数据:

$.ajax("x", {
    data: { data: [this.name, this.description, this.pages] },
    type: "post", 
    success: function(result) { alert(result) },
    error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});

现在看看里面$_POST["data"]

或者如果您需要使用 JSON 请求,则需要将其反序列化回您的 PHP 文件中:

$.ajax("x", {
    data: { data: ko.toJSON([this.name, this.description, this.pages]) },
    type: "post", 
    success: function(result) { alert(result) },
    error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});

然后解码:

$json = $_POST['json'];
$data = json_decode($json);

如果你想在 POST 正文中发送纯 JSON 请求:

$.ajax("x", {
    data: ko.toJSON([this.name, this.description, this.pages]),
    type: "post", 
    contentType: 'application/json',
    success: function(result) { alert(result) },
    error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});

进而:

$data = json_decode(file_get_contents("php://input"));

请注意,这php://input是一个只读流,允许您从请求正文中读取原始数据。

于 2012-09-11T07:06:10.347 回答