2012-09-11 120 views
0

我正在发起一个HTTP POST请求与Ajax到我的PHP文件,但我没有得到所需的结果。 $ _POST和$ _GET都是空的。我想我忽略了一些东西,但我不知道是什么。Ajax POST请求没有通过到PHP

这里是我的烧制的请求代码:

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)} 
    }); 
}; 

注意,我提醒JSON上线3. 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测试了它,得到了类似的负面结果。
+0

你能写出ko.toJSON([this.name,this.description,this.pages])的输出吗? –

+0

你可以在KnockoutJS中使用这个操作符吗?在这一行:ko.toJSON([this.name,this.description,this.pages])。有一些关于这个和自我的文档。 – JvdBerg

+0

'[“Name”,“Description”,[{“title”:“Page 1”,“selectedPageStyle”:“Header”}]]' – Sherlock

回答

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是一个只读流,允许您从请求主体读取原始数据。

+0

我想把它作为JSON发送。在我使用的示例中(请参阅http://learn.knockoutjs.com/#/?tutorial=loadingsaving)使用POST发送JSON。为什么我不能合并JSON和POST?我第一次听说tbh .. – Sherlock

+0

你可以结合起来,看看我的第二个例子。 –

+0

由于某种原因,我现在没有得到任何结果。 (我明显改变了网址。)网址是正确的,但成功警报或错误警报触发......我会尝试调试。 – Sherlock