简体   繁体   中英

Result of Array.map is undefined in Ajax request

I have very confusing behaviour in javascript. The body of HTTP request is undefined=&undefined= .

var data = [1, 2].map(function(item) {
    return {
        Id: item,
        Quantity: 1
    }
});

$.ajax({
    url: "someUrl",
    type: "POST",
    dataType: "json",
    data: data
});

How can I prevent from losing data? Please advise.

The problem is that you are posting data with Content-Type:application/x-www-form-urlencoded header. Check documentation for $.ajax . In this case data passed will be serialized with $.param method, which if you check documentation does the following:

Create a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input elements with name/value properties.

And now you know why the data is posted as

undefined=undefined&undefined=undefined

Finally, if you want to post a JSON payload you can stringify data yourself and add application/json content-type:

$.ajax({
    url: "someUrl",
    type: "POST",
    dataType: "json",
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8"
});

The data attribute in ajax function is not the data returned from the ajax execution. It is the data sent to it.

Use the success callback function to manipulate the data returned

$.ajax({
    url: "someUrl",
    type: "POST",
    dataType: "json",
    data: data,
    success: function(dataReturned) {
       // Do something with dataReturned
    }
});

Take a look at the documentation

You need to stringify your data object in order for it to be retrievable via $_POST at the destination.

var data = [1, 2].map(function(item) {
    return {
        Id: item,
        Quantity: 1
    }
});
$.ajax({
    async: false,
    url: 'someUrl',
    method: 'post',
    dataType: 'json',
    data: 'data=' + JSON.stringify(data) /** <---- here; add a to retrieve on other end; in this case 'data=' */
});

Then to access it within your someUrl you can decode it using json_decode() :

$json = json_decode($_POST['data']);

Becomes:

$json = Array
(
    [0] => stdClass Object
        (
            [Id] => 1
            [Quantity] => 1
        )

    [1] => stdClass Object
        (
            [Id] => 2
            [Quantity] => 1
        )

)

echo $json[0]->Id; // 1

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