min*_*pop 1 javascript php ajax jquery request
我正在尝试使用JQuery将类似于下面的数据结构传递给php脚本:
{
"shopping":
[
{
"type": "online",
"mood": 9
},
{
"type": "mood",
"mood": 4
}
],
"researching":
[
{
"type": "online",
"mood": 3
},
{
"type": "library",
"mood": 1
}
]
}
Run Code Online (Sandbox Code Playgroud)
JSON中的这些数据会根据用户操作的表单和滑块进行更改,然后使用提交按钮异步发送JSON.我无法弄清楚如何使用JQuery提交此请求,以及如何让PHP解析它.我想使用POST方法发送此数据.现在,我正在使用:
$.post('server/dataInput.php',submissions, function(data){
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
提交是JSON对象的位置,但这似乎不起作用.我也不知道如何在PHP结束时解析这个JSON.
如果您使用的是jquery 1.4.0+ 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); });
}
Run Code Online (Sandbox Code Playgroud)
打电话sendTest......
test.php的:
<?php
var_dump($_POST);
Run Code Online (Sandbox Code Playgroud)
并且您的成功函数将显示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"
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以,一切都是开箱即用的!:)