Send array with jquery $ .ajax

I am trying to pass an array to ajax. Here is the code (productOptions - ARRAY)

data: { action:'add',tblID : tblID, option:productOptions},

as far as I know that this approach (using objects) jquery does the job, but I don't get the parameter parameter at all (EXPLAIN BELOW).

NOTIFICATION:

var productOptions=new Array();
    productOptions[0]="test1";
    productOptions[1]="test2";

with the above array i get productOptions

var productOptions=new Array();
        productOptions['color']="test1";
        productOptions['size]="test2";

i DO NOT ALLOW productOptions

Any help plz

+3
source share
1 answer

Solution first

Make productOptionsa Objectinstead Arrayand use jQuery.extend()to combine productOptionswith the rest of the data that will be used in the ajax request.

var productOptions = new Object();
productOptions['color']="test1";
productOptions['size']="test2";

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script",
  data: jQuery.extend({action: 'add'}, productOptions)
});

Productivity GET test.js?_=randomjQueryNumber&action=add&color=test1&size=test2


Long explanation

, , Array . , . (key, value).

,

1

var productOptions=new Array();
productOptions[0]="test1";
productOptions[1]="test2";
alert(productOptions.length); //yields 2

: , , productOptions[0] productOptions[4], 5!

2

var productOptions=new Array();
productOptions['color']="test1";
productOptions['size]="test2";
alert(productOptions.length); //yields 0

1 productOptions[0]="test1"; productOptions.push("test1"); ( - 1 - push , ).

2 productOptions['color']="test1"; ""; , javascript-, color test1 .

, , javascript color size.

alert(productOptions.color); //yields test1
alert(productOptions.size); //yields test2
alert(productOptions[0]); //yields undefined

1. productOptions - , jQuery , option=test1&option=test2.

jQuery, option:productOptions option:new Array();

+9

Source: https://habr.com/ru/post/1725032/


All Articles