我有一个多维数组,我试图通过jQuery ajax调用我的PHP脚本传入数据。
我使用以下代码声明了lobby_state:
lobby_state = [];
lobby_state.users = 3;
lobby_state.user = [];
lobby_state.user[0].username = 'john';
lobby_state.user[0].age = 30;
lobby_state.user[0].sex = 'M';
lobby_state.user[1].username = 'kim';
lobby_state.user[1].age = 17;
lobby_state.user[1].sex = 'F';
lobby_state.user[2].username = 'mary';
lobby_state.user[2].age = 51;
lobby_state.user[2].sex = 'F';
我传递了总共2个值,一个简单的字符串和多维数组:
$.ajax({
type: "POST",
url: "app/lobby/lobby-process.php",
data: {
'action': 'update',
'state': lobby_state
},
dataType: "json",
success: function(data){
...
当我执行此操作时,它似乎完全忽略了lobby_state值,并且只传递了'action'值,如下面的Chrome开发者控制台请求值所示。
我尝试了所有传递数组的例子,但似乎没有任何效果。我错过了什么吗?
答案 0 :(得分:1)
您需要将其作为JSON字符串传递:
state: JSON.stringify(lobby_state)
关于如何正确声明数组的示例:
var lobby_state = [],
john = { username: 'john', age: 30, sex: 'M' };
lobby_state.push(john);
console.log(lobby_state);
您也可以直接将对象添加到数组中:
var lobby_state = [{ username: 'john', age: 30, sex: 'M' }];