How do I receive a JSON file using AJAX and parse it using javascript?

懵懂的女人 提交于 2019-12-01 01:49:49

You should do:

$.ajax({
    // some other code
    success: getVenues
});

You are telling ajax: "use getVenues function", not "use getVenus(data) value". As for second question:

var l = data.response.groups.length;
for (var i = 0; i < l; i++) {
    var group = data.response.groups[i];
    var k = group.items.length;
    for (var j = 0; j < k; j++) {
        var venue = group.items[j].venue;
        // use venue as you wish
    }
}

The tutorials you see online are likely declaring the success callback as an anonymous function. In those cases, data isn't being passed to a function, it's being declared as the parameter of that function. jQuery is nice enough to handle passing the response from the AJAX call to the success function as the first parameter, whatever you choose to name it (data just makes the most sense).

Additionally, if you specify dataType: 'json' on your $.ajax() call, jQuery will parse the JSON response before passing it to that function, ensuring that it's valid JSON and that you have an object to work with inside the function. If the response isn't valid JSON, the success callback won't be executed, and instead the error callback (if you've specified one) will be executed.

In your case, you're passing a function reference, so assuming your getVenuesfunction looks like this:

function getVenues(data) {
    // do something
}

then you can simply do:

success: getVenues

in the object you're passing to $.ajax().

The success property of the object in your ajax call just needs function name or an function object. You either give it just the name, like that:

    $.ajax({
      url: 'https://api.foursquare.com/v2/venues/explore',
      dataType: 'json',
      data: 'limit=7&ll='+latitude+','+longitude+'&client_id='+client_id+'&client_secret='+client_secret+'',
      async: false,
      success: getVenues
});

or you do this:

  $.ajax({
      url: 'https://api.foursquare.com/v2/venues/explore',
      dataType: 'json',
      data: 'limit=7&ll='+latitude+','+longitude+'&client_id='+client_id+'&client_secret='+client_secret+'',
      async: false,
      success: function(data) { getVenues(data) }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!