2015-11-23 198 views
1

我已經做了幾次嘗試來捕獲一個json結果到一個全局變量中,但它不斷回來未定義。任何線索,我做錯了什麼?JSON調用返回undefined

var temp; 
     var temp2; 
    function getCount() { 

     var jqxhr = $.getJSON("Data/OutageCountHandler.ashx", function({ 
temp = jqxhr.responseText; //attempt to assign data to global variable. returns undefined. 
       console.log("success"); 
     }) 
     .done(function (data) { 
      console.log("second success"); 
      console.log(jqxhr.responseText); //returns the number but only in log 
      console.log(data); //returns the number but only in log 
      console.log(data.d); //returns undefined 
      temp2= jqxhr.responseText; //second attempt returns undefined. 
      temp3 = data; //returns undefined 
      temp4 = data.d; //returns undefined 
     }) 
     .fail(function() { 
     console.log("error"); 
     }) 

     .always(function() { 
      console.log("complete"); 
     }); 
      temp5 = jqxhr.responseText; returns undefined. 
     jqxhr.complete(function() { 
      console.log("second complete"); 
     }); 
     temp6 = jqxhr.responseText; //returns undefined 
     return jqxhr.responseText; //returns undefined 
    } 

我也嘗試過這種方式,但相同的結果

function getCount() { 
    var results = null; 
    $.getJSON("Data/OutageCountHandler.ashx", function (data) { 

     temp = data;  //returns null 
     temp2 = data.d; //returns undefined 
     results = data; //returns null 
    }); 

    return results; //returns null 
} 
+0

我試着在其他線程使用的分辨率,請重新打開,因爲我真的很需要這方面的 –

回答

0
temp = jqxhr[0].responseText; //attempt to assign data to global variable. returns undefined. 
       console.log("success"); 

嘗試在[0]後jqxhr增加。這可能會解決您的問題。

+0

它說幫助0x800a138f - JavaScript的運行時錯誤:無法獲取的未定義或空引用 –

+0

財產「responseText的」什麼是您的控制檯日誌的輸出? –

+0

成功第二次成功,81,81,未定義,完成,第二次完成 –