[英]Posting and parsing data sent from JQuery to PHP
我正在嘗試使用JQuery將類似於以下內容的數據結構傳遞給php腳本:
{
"shopping":
[
{
"type": "online",
"mood": 9
},
{
"type": "mood",
"mood": 4
}
],
"researching":
[
{
"type": "online",
"mood": 3
},
{
"type": "library",
"mood": 1
}
]
}
JSON中的此數據根據用戶操作的形式和滑塊而變化,然后使用提交按鈕以異步方式發送JSON。 我在弄清楚如何使用JQuery提交此請求以及如何讓PHP解析它時遇到了麻煩。 我想使用POST方法發送此數據。 現在,我正在使用:
$.post('server/dataInput.php',submissions, function(data){
console.log(data);
});
提交是JSON對象,但是這似乎不起作用。 我也不知道如何在PHP的末尾解析此JSON。
如果您使用的是jQuery json_decode
則不需要json_decode
。 您的數據將以數組形式在PHP中接收。
例:
JS片段:
var testData = {
"shopping": [
{
"type": "online",
"mood": 9
},
{
"type": "mood",
"mood": 4
}
],
"researching": [
{
"type": "online",
"mood": 3
},
{
"type": "library",
"mood": 1
}
]
};
function sendTest() {
$.post('test.php', testData, function(data) { console.log(data); });
}
呼叫sendTest
...
test.php:
<?php
var_dump($_POST);
您的成功函數將顯示test.php
輸出的內容:
array(2)
{
["shopping"]=> array(2)
{
[0]=> array(2)
{
["type"]=> string(6) "online"
["mood"]=> string(1) "9"
}
[1]=> array(2)
{
["type"]=> string(4) "mood"
["mood"]=> string(1) "4"
}
}
["researching"]=> array(2)
{
[0]=> array(2)
{
["type"]=> string(6) "online"
["mood"]=> string(1) "3"
}
[1]=> array(2)
{
["type"]=> string(7) "library"
["mood"]=> string(1) "1"
}
}
}
因此,所有東西都開箱即用! :)
您應該使用PHP json_decode解壓縮JSON數據嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.