简体   繁体   中英

GET JSON Data from AJAX request

I have a URL with JSON Data. I cannot get this to work because I do not know what to put in the data field. Data is not defined, but it is there as a placeholder for now. What I want to do is save an array of the JSON data I get from the ajax request. What am I doing wrong?

$.ajax({
    type: "GET",
    url: url,
    dataType: "json",
    data: data,
    success: function(data) {
        console.log(data);
    },
    error: function() {
        console.log("error");
    }
});
$.getJSON( url, function( data ) { 
  console.log(data); 
});

More examples in jQuery official documentation .

You do not need to put anything in the data. The parameter "data" is the response getting from the server.

Use following:

$.ajax({
        url: 'serverurl',  //write your server url here...
        dataType: 'json',  //The data type expected of the server response.
        success: function(data) {
            myServerData = data;  //server response
        }
});

Once you get JSON object myServerData, to convert it into JavaScript array use following jQuery:

var arr = $.map( myServerData, function(param) { return param; } );

from JQuery documentation : data is

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.

so data could be a string, eg:

data: "firstParam=foo&secondParam=bar"

or a data structure, eg:

data: {
  firstParam: "foo",
  secondParam=bar
}

if you don't need any params, simply omit it in your ajax call.

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