[英]Posting and parsing data sent from JQuery to PHP
I'm trying to use JQuery to pass a data structure that looks similar to the one below to a php script: 我正在尝试使用JQuery将类似于以下内容的数据结构传递给php脚本:
{
"shopping":
[
{
"type": "online",
"mood": 9
},
{
"type": "mood",
"mood": 4
}
],
"researching":
[
{
"type": "online",
"mood": 3
},
{
"type": "library",
"mood": 1
}
]
}
This data in the JSON changes based on forms and sliders a user manipulates, and then the JSON is sent asynchrounously with a submit button. JSON中的此数据根据用户操作的形式和滑块而变化,然后使用提交按钮以异步方式发送JSON。 I am having trouble figuring out how to use JQuery to submit this request, and how to have PHP parse it. 我在弄清楚如何使用JQuery提交此请求以及如何让PHP解析它时遇到了麻烦。 I would like to send this data using the POST method. 我想使用POST方法发送此数据。 Right now, I'm using: 现在,我正在使用:
$.post('server/dataInput.php',submissions, function(data){
console.log(data);
});
Where submissions is the JSON object, however this doesn't seem to be working. 提交是JSON对象,但是这似乎不起作用。 I also dont' know how I would then parse this JSON on PHP's end. 我也不知道如何在PHP的末尾解析此JSON。
If you are using jquery 1.4.0+ json_decode
is not necessary. 如果您使用的是jQuery json_decode
则不需要json_decode
。 Your data will be received in PHP as an array. 您的数据将以数组形式在PHP中接收。
Example: 例:
JS fragment: 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); });
}
Call sendTest
... 呼叫sendTest
...
test.php: test.php:
<?php
var_dump($_POST);
And your success function will display what test.php
outputted: 您的成功函数将显示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"
}
}
}
So, everything works out-of-the-box! 因此,所有东西都开箱即用! :) :)
您应该使用PHP json_decode解压缩JSON数据吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.