Send a JavaScript array as a JSON value?

2020-06-03 08:56发布

问题:

How can I send a JavaScript array as a JSON variable in my AJAX request?

回答1:

This requires you to serialize the javascript array into a string, something that can easily be done using the JSON object.

var myArray = [1, 2, 3];
var myJson = JSON.stringify(myArray); // "[1,2,3]"
....
xhr.send({
    data:{
        param: myJson
    }
});

As the JSON object is not present in older browsers you should include Douglas Crockfords json2 library

If you already rely on some library that includes methods for encoding/serializing then you can use this instead. E.g. ExtJs has Ext.encode



回答2:

If you're not using a javascript library (jQuery, prototype.js, etc) that will do this for you, you can always use the example code from json.org



回答3:

Just encode the array and send it as part of your AJAX recuest:

http://www.openjs.com/scripts/data/json_encode.php

There are too many others encoders, or even plugins for JQuery and Mootools :D



回答4:

Here's an example:

 var arr = [1, 2, 3];
 $.ajax({
        url: "get.php",
        type: "POST",
        data: {ids:arr},
        dataType: "json",
        async: false,
        success: function(data){
            alert(data);
        }
    });

In get.php:

echo json_encode($_POST['ids']);

Array will be converted to object using {ids:arr}, pass the object itself and letting jQuery do the query string formatting.