简体   繁体   中英

Array associative from JavaScript-Ajax to php

in this exercise, I need to edit books quantitys on a form, and then pass it from javascript-ajax to php-sql.

But, first, my form looks like this (generated by php), and as you can see, books id's into "name".

<input type="text" class="bookclass" name="books[1]" />
<input type="text" class="bookclass" name="books[2]" />    
<input type="text" class="bookclass" name="books[3]" />    

Ok, now, I need to get all values (quantitys).

var arr = new Array();
var elems = document.querySelectorAll('.bookclass'); // class

    for ( var i=0; i<elems.length; i++ ) {
        arr.push(elems[i].value)

    }    

But, of course, when I use "push" method, isn't associative.

Ajax send:

xmlhttp.open("GET", "edit.php?q=" + arrayassoc, true);

So, how can I do?

Use the name and values of the inputs instead of making up a new key name and then trying to stringify an array onto it.

var query_string = "?";

for ( var i=0; i<elems.length; i++ ) {
    query_string += encodeURIComponent(elems[i].name) + "=" +
                    encodeURIComponent(elems[i].value) + "&";
}    

xmlhttp.open("GET", "edit.php" + query_string, true);

JavaScript does not support associative arrays.

You can use below code .

    var arr = [];
    var elems = document.querySelectorAll('.bookclass'); // class

    for ( var i=0; i<elems.length; i++ ) {

        arr[i]   = elems[i].value;

    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM