jQuery. Assign JSON as a result to a variable

前端 未结 3 1171
走了就别回头了
走了就别回头了 2020-12-21 16:16

I use this helper function to receive JSON results for my requests:

function getData(url) {
    $.get(url,
         function(data) {
             response =          


        
3条回答
  •  醉梦人生
    2020-12-21 16:32

    It's an asynchronous operation, meaning that function(data) { ... } runs later when the response from the server is available, long after you returned from getData(). Instead, kick off whatever you need from that function, for example:

    function getData(url, callback) {
        $.get(url, callback, 'application/json');
    }
    

    Then when you're calling it, pass in a function or reference to a function that uses the response, like this:

    getData("myPage.php", function(data) {
      alert("The data returned was: " + data);
    });
    

提交回复
热议问题