【问题标题】:Ajax POST-request doesn't come through to PHPAjax POST 请求未通过 PHP
【发布时间】:2012-09-04 01:41:08
【问题描述】:

我正在使用 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 对其进行了测试,结果相似。

【问题讨论】:

  • 你能写出 ko.toJSON([this.name, this.description, this.pages]) 的输出吗?
  • 可以在 KnockoutJS 中使用 this 操作符吗?在这一行中:ko.toJSON([this.name, this.description, this.pages])。有一些关于 this 和 self 的文档。
  • ["Name","Description",[{"title":"Page 1","selectedPageStyle":"Header"}]]
  • json应该使用控制台,PHP中不需要设置header。
  • 我们不必为此使用 dataType : 'json' 吗?

标签: php javascript jquery


【解决方案1】:

您正在发送 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 是一个只读流,允许您从请求正文中读取原始数据。

【讨论】:

  • 我想以 JSON 格式发送。在我使用的示例中(参见此处learn.knockoutjs.com/#/?tutorial=loadingsaving),JSON 是使用 POST 发送的。为什么我不能结合 JSON 和 POST?我第一次听说这个tbh..
  • 可以结合,看我的第二个例子。
  • 由于某种原因,我现在根本没有得到任何结果。 (我明显改了url。)url是正确的,但是成功提示和错误提示都会触发...我会尝试调试。
  • 您使用的是 3 种方法中的哪一种?试试 FireBug。
  • 这是 Opera 的问题,在 Firefox 中确实有效。非常感谢!我会弄清楚 Opera 的问题是什么。我现在正在使用第三个。
猜你喜欢
  • 2018-09-26
  • 2020-05-29
  • 1970-01-01
  • 2016-01-18
  • 1970-01-01
  • 1970-01-01
  • 2018-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多