使用 jquery ajax 发布一个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5795735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:49:57  来源:igfitidea点击:

post an array using jquery ajax

jsonpostjquery

提问by Daniel

I am trying to do something fairly simple but I can't seem to find the solution. I want to post a multi-dimensional array to a php page using jQuery's .ajax function, but I can't seem to serialize the array properly.

我正在尝试做一些相当简单的事情,但似乎找不到解决方案。我想使用 jQuery 的 .ajax 函数将多维数组发布到 php 页面,但我似乎无法正确序列化该数组。

The code is as follows

代码如下

var dataToSend = new Array();
  dataToSend["page"] = location.href;
  dataToSend["data"] = new Array();
  var dataindex = 0;
  jQuery(".myclass").each(function(){
      dataToSend["data"][dataindex]=new Array();
      dataToSend["data"][dataindex]["selector"] = unique_selector(jQuery(this), "");
      dataToSend["data"][dataindex]["contents"] = jQuery(dataToSend["data"][dataindex]["selector"]).html();
  });
  jQuery.ajax({
      type: 'POST',
      url: "/main/save.php",
      data: JSON.stringify(dataToSend),
      dataType: "json",
      success: function(data){alert(data);}
  });

basically I am not sure how to properly pass the dataToSend array. Right now firebug show the post as empty even though the array is loaded with all kinds of good stuff.

基本上我不确定如何正确传递 dataToSend 数组。现在,即使数组加载了各种好东西,firebug 仍将帖子显示为空。

Thanks,

谢谢,

Daniel

丹尼尔

回答by jerone

You're defining new Array();, but you're using them as new Object(). Try using objects.

您正在定义new Array();,但您将它们用作new Object(). 尝试使用对象。

Try this:

尝试这个:

var dataToSend = { 
    page: location.href, 
    data: []
};
var dataindex = 0;
jQuery(".myclass").each(function(){
    var temp = unique_selector(jQuery(this), "");
    dataToSend.data[dataindex++] = {
        selector: temp,
        contents: jQuery(temp).html()
    };
});
jQuery.ajax({
    type: 'POST',
    url: "/main/save.php",
    data: JSON.stringify(dataToSend),
    dataType: "json",
    success: function(data){ alert(data); }
});

回答by slandau

Taken from the PHP help pages:

取自 PHP 帮助页面:

you may have multidimensional array in form inputs

您可能在表单输入中有多维数组

HTML Example:

HTML 示例:

<input name="data[User][firstname]" type="text" />
<input name="data[User][lastname]" type="text" />
...

Inside php script after submit you can access the individual element like so:

提交后在 php 脚本中,您可以像这样访问单个元素:

$firstname = $_POST['data']['User']['firstname'];
...

回答by Mukesh Agarwal

Use

data: { '': dataToSend }

I used this in a similar scenario and it worked like charm...

我在类似的场景中使用了它,它的作用就像魅力......