简体   繁体   中英

sending a two dimension array from JavaScript to php and vice versa

i use this code to send one dimension array of integer but how to make it sending and receiving two dimension array formed by combination of integer and string eg [number here]["text here"] but the url has a limit so that i can't make a big array

//Send data to php
                var queryString ="?";
                            for(var t=0;t<alldays.length;t++)
                                {   
                                    if(t==alldays.length-1)
                                    queryString+="arr[]="+alldays[t];
                                    else
                                    queryString+="arr[]="+alldays[t]+"&";
                                }
                ajaxRequest.open("POST", "forbidden.php" + queryString, true);
                ajaxRequest.send(null); 

            }

// Create a function that will receive data sent from the server(sended as echo json_encode($array))
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){

        var myArray = ajaxRequest.responseText.replace("[","").replace("]","").replace(/"/g,"").split(",");
        for(var i=0; i<myArray.length; i++) { alldays[i] = parseInt(myArray[i]); } 

        }}

Instead of including the request as a query string added to the url, send it as the body of the POST:

var queryString ="";
for(var t=0;t<alldays.length;t++)
{
    if(t==alldays.length-1)
        queryString+="arr[]="+alldays[t];
    else
        queryString+="arr[]="+alldays[t]+"&";
}
ajaxRequest.open("POST", "forbidden.php", true);
ajaxRequest.send(queryString); 

There aren't the same restrictions on the query length if its sent as the POST body.

However, all your POST variables are named "arr[]" , which is going to cause problems. I suggest the following encoding scheme instead:

var queryString = "n=" + alldays.length;
for (var t=0; t<alldays.length; t++)
{
    queryString += "&arr_" + t + "=" + alldays[t];
}
ajaxRequest.open("POST", "forbidden.php", true);
ajaxRequest.send(queryString); 

Then on the server you can retrieve the number of array elements with $_POST["n"] and then process $_POST["arr_" + t] for each t from 0 to n-1 .

You do use a POST request - so don't send the array in the GET parameters of the query string!

var queryString =""; // no question mark
// construct rest of query string here
ajaxRequest.open("POST", "forbidden.php", true);
ajaxRequest.send(queryString);

Also, use JSON for the response. PHP-side: json_encode , JavaScript-side: JSON.parse

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