[英]jquery.ajax set with async=true to send data back to server not working if page redirects/reloads
[英]send json data to server jquery.ajax
不幸的是,另一個與json相關的問題...
考慮以下json
[{"details":{
"forename":"Barack",
"surname":"Obama",
"company":"government",
"email":"bigcheese@whitehouse.com",
"files": [{
"title":"file1","url":"somefile.pdf"
},
{
"title":"file2",
"url":"somefile.pdf"
}]
}
}]
我需要將此數據發送到服務器上的php腳本,然后在服務器上與之交互,但不知道如何。
我通過jquery.ajax發送它,並且發送得很好(沒有錯誤消息),這里是代碼。 (newJson是我完全如上所述創建的json對象)
$.ajax({
type: "POST",
url: "test.php",
dataType: 'json',
data: newJson,
success: function(msg)
{
alert(msg);
},
error: function(jqXHR, textStatus)
{
alert(textStatus);
}
});
所以到目前為止,在我的php腳本中,我只想將內容作為字符串回顯,該字符串將顯示在成功警報中
<?php
header('Access-Control-Allow-Origin: *');
echo $_POST;
?>
但這只是給我一個解析錯誤..那么,有什么好主意的人嗎?
您必須有一個鍵/值對,才能使用$_POST[key]
接收php中的數據。 獨自發送所有數組不是最好的方法,因為您已經具有對象的結構
我將解開外部數組,因為您僅在其中發送了一個對象
然后對象看起來像
{"details":{
"forename":"Barack",
"surname":"Obama",
"company":"government",
"email":"bigcheese@whitehouse.com",
"files": [{
"title":"file1","url":"somefile.pdf"
},
{
"title":"file2",
"url":"somefile.pdf"
}]
}
}
在php中會收到$_POST['details']
。 不轉換為JSON,只需將整個對象傳遞給$.ajax data
屬性。
如果您從ajax收到parserror
,則是在接收方,聽起來像是從php獲取500錯誤或未按dataType
預期發送回json
首先,原始JSON字符串格式錯誤。 嘗試
{
"details":{
"forename":"Barack",
"surname":"Obama",
"company":"government",
"email":"bigcheese@whitehouse.com",
"files": [
{ "title":"file1","url":"somefile.pdf" },
{ "title":"file2","url":"somefile.pdf"}
]
}
}
其次,發送到PHP的數據已經解析為一個數組,但不是JSON。 要回顯,必須使用json_encode將數組轉換回JSON字符串
echo json_encode($_POST);
exit;
由於您沒有將JSON作為字段傳遞,因此可以執行以下操作:
<?php
$post = file_get_contents("php://input");
$json = json_decode($post);
var_dump($json); // Should be a nice object for you.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.