开发者

post an array using jquery ajax

开发者 https://www.devze.com 2023-03-01 08:54 出处:网络
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

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.

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开发者_StackOverflow]["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.

Thanks,

Daniel


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

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); }
});


Use

data: { '': dataToSend }

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


Taken from the PHP help pages:

you may have multidimensional array in form inputs

HTML Example:

<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:

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

精彩评论

暂无评论...
验证码 换一张
取 消