最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

passing data in javascript array to server with jQuery.ajax post function? - Stack Overflow

programmeradmin6浏览0评论

I was wondering if its possible to pass data stored in a javascript array to the server using jQuery's ajax function..

In the jQuery documentation it specifies:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

can "data" be set to an array? How would this work given it seems data is expecting key value pairs? I currently just hard code the values but I want it to be a more dynamic approach..my current code is:

jQuery.ajax({
            url: "/createtrips/updateitin",
            type: 'POST',
            data: {place1: 'Sydney', place2: 'London'},
            dataType: 'json',
            });

I was wondering if its possible to pass data stored in a javascript array to the server using jQuery's ajax function..

In the jQuery documentation it specifies:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

can "data" be set to an array? How would this work given it seems data is expecting key value pairs? I currently just hard code the values but I want it to be a more dynamic approach..my current code is:

jQuery.ajax({
            url: "/createtrips/updateitin",
            type: 'POST',
            data: {place1: 'Sydney', place2: 'London'},
            dataType: 'json',
            });
Share Improve this question asked Dec 25, 2011 at 21:46 RowanRowan 4633 gold badges8 silver badges20 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8

I created an array like this:

var placesfortrip = {};

then added to it like this:

placesfortrip["item"+counter] = inputVal;

(where counter is an incremented counter variable) then assigned this to the data property of the ajax call

 jQuery.ajax({
            url: "/createtrips/updateitin",
            type: 'POST',
            data: placesfortrip,
            dataType: 'json',
            });

and if I look at the XHR tab in firebug it appears those values get posted!

Yes, jQuery.ajax() supports the passing of arrays. It simply serializes the array into a name-value string.

If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

I believe you would like to look into using JSON to pass those values.

This is a good place to start

Check out jQuery serialize: http://api.jquery./serialize/

$('form').submit(function() {
  alert($(this).serialize());
  return false;
});
This produces a standard-looking query string:

a=1&b=2&c=3&d=4&e=5
发布评论

评论列表(0)

  1. 暂无评论