Pass array to ajax request in $.ajax() [duplicate]

2019-01-01 06:55发布

Possible Duplicate:
Serializing to JSON in jQuery

I want to send an array as an Ajax request:

info[0] = 'hi';
info[1] = 'hello';

$.ajax({
  type: "POST",
  url: "index.php",
  success: function(msg){
    $('.answer').html(msg);
  }
});

How can I do this?

3条回答
ら面具成の殇う
2楼-- · 2019-01-01 07:22

NOTE: Doesn't work on newer versions of jQuery.

Since you are using jQuery please use it's seralize function to serialize data and then pass it into the data parameter of ajax call:

info[0] = 'hi';
info[1] = 'hello';

var data_to_send = $.serialize(info);

$.ajax({
    type: "POST",
    url: "index.php",
    data: data_to_send,
    success: function(msg){
        $('.answer').html(msg);
    }
});
查看更多
忆尘夕之涩
3楼-- · 2019-01-01 07:27

Just use the JSON.stringify method and pass it through as the "data" parameter for the $.ajax function, like follows:

$.ajax({
    type: "POST",
    url: "index.php",
    dataType: "json",
    data: JSON.stringify({ paramName: info }),
    success: function(msg){
        $('.answer').html(msg);
    }
});

You just need to make sure you include the JSON2.js file in your page...

查看更多
与风俱净
4楼-- · 2019-01-01 07:38
info = [];
info[0] = 'hi';
info[1] = 'hello';


$.ajax({
   type: "POST",
   data: {info:info},
   url: "index.php",
   success: function(msg){
     $('.answer').html(msg);
   }
});
查看更多
登录 后发表回答