jQuery. Assign JSON as a result to a variable

前端 未结 3 1172
走了就别回头了
走了就别回头了 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);
    });
    
    0 讨论(0)
  • 2020-12-21 16:41

    Use $.ajax

    $.ajax({
        url: 'http://www.example.com',
        dataType: 'json',
        success: function(data){
           alert(data.Id);
        }
    });
    
    0 讨论(0)
  • 2020-12-21 16:43

    try this

    function getData(url) {
    var data;
        $.ajax({
            async: false, //thats the trick
            url: 'http://www.example.com',
            dataType: 'json',
            success: function(response){
               data = response;
            }
        });
        return data;
    }
    
    0 讨论(0)
提交回复
热议问题