I've got the jQuery code:
我有jQuery代码:
$(document).ready(function() {
answers = new Array();
answers[0] = new Array();
answers[0]['question_id'] = 12;
answers[0]['answer_id'] = 32;
answers[1] = new Array();
answers[1]['question_id'] = 55;
answers[1]['answer_id'] = 132;
answers[2] = new Array();
answers[2]['question_id'] = 987;
answers[2]['answer_id'] = 1112;
$.ajax({
type: "POST",
url: "collect.php",
data: {answers: answers},
dataType: "json",
beforeSend:function(){
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
},
success: function(data){
alert('success!');
}
});
});
});
Now, should this work? According to what I've found when looking for code examples it should. Problem is, I have no idea how I could collect the data in my PHP file. I mean, it's a $_POST[], but then what? How do I collect the $result[0]['question_id'] and all the other data?
现在,这应该工作吗?根据我在寻找代码示例时发现的内容。问题是,我不知道如何在PHP文件中收集数据。我的意思是,它是一个$ _POST [],但那么呢?如何收集$ result [0] ['question_id']和所有其他数据?
Thanks a lot in advance,
非常感谢提前,
Carl C. Carlsson
Carl C. Carlsson
3 个解决方案
#1
2
You're never actually populating the arrays inside of the answers array with data, their length is still 0 because you're using string indexes rather than int indexes. What you really want are objects stored in your array.
你实际上从来没有用数据填充answers数组中的数组,它们的长度仍为0,因为你使用的是字符串索引而不是int索引。你真正想要的是存储在你的数组中的对象。
answers[0] = {};
answers[0]['question_id'] = 12;
answers[0]['answer_id'] = 32;
#2
1
You can collect the value in php page with $_POST['answers']
. Then you can loop through that array do whatever you want with the data.
您可以使用$ _POST ['answers']在php页面中收集值。然后你可以循环遍历该数组,随心所欲地处理数据。
#3
1
It was solved by changing the Javascript to:
通过将Javascript更改为:
answers = {};
I could then simply access the data in PHP with:
然后,我可以使用以下方法访问PHP中的数据:
$_POST['answers'][1]['answer_id'];
for example, or just loop through it.
例如,或者只是循环它。
Thanks for your help, ladies and gentlemen.
谢谢你的帮助,女士们,先生们。
#1
2
You're never actually populating the arrays inside of the answers array with data, their length is still 0 because you're using string indexes rather than int indexes. What you really want are objects stored in your array.
你实际上从来没有用数据填充answers数组中的数组,它们的长度仍为0,因为你使用的是字符串索引而不是int索引。你真正想要的是存储在你的数组中的对象。
answers[0] = {};
answers[0]['question_id'] = 12;
answers[0]['answer_id'] = 32;
#2
1
You can collect the value in php page with $_POST['answers']
. Then you can loop through that array do whatever you want with the data.
您可以使用$ _POST ['answers']在php页面中收集值。然后你可以循环遍历该数组,随心所欲地处理数据。
#3
1
It was solved by changing the Javascript to:
通过将Javascript更改为:
answers = {};
I could then simply access the data in PHP with:
然后,我可以使用以下方法访问PHP中的数据:
$_POST['answers'][1]['answer_id'];
for example, or just loop through it.
例如,或者只是循环它。
Thanks for your help, ladies and gentlemen.
谢谢你的帮助,女士们,先生们。