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

前端 未结 3 1959
深忆病人
深忆病人 2021-01-07 14:13

I\'m trying to parse this very long and complicated JSON that foursquare gives me. This is my AJAX request:

    $.ajax({
      url: \'https://api.foursquare.         


        
3条回答
  •  轮回少年
    2021-01-07 14:38

    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().

提交回复
热议问题