2012-05-21 62 views
0

我現在正在開發的代碼的想法是從JSON文件(我從服務器獲取)中提取數據,然後使用美麗的漂亮的圖形。問題是我無法檢索將JSON結果保存在Jquery代碼中的對象,因此我可以將它們加載到圖形中。 爲了簡化,我的代碼是這樣的(JavaScript部分)如何從JavaScript調用JQuery函數(異步調用後)

var obj; //I initialize it here in order to make it global though it doesn't work 

function handle_json() { 
    if (http_request.readyState == 4) { 
    if (http_request.status == 200) { 
     var json_data = http_request.responseText; 
     obj = eval("(" + json_data + ")"); 
     //at this point I have the information I want in "obj" 
} else { 
    alert("A problem ocurred."); 
} 
http_request = null; 

} }

但現在我要發「OBJ」我的jQuery的代碼,所以我可以接觸到的信息,並顯示它。 但是,如果嘗試這種(jQuery的部分)

$(function() { 
alert(obj.results.bindings[0].a.value); //<-- this doesn't work, obj isn't initialized 
var fert = []; 
fert = [[1990, 1.28], [1995, 1.25], [2000, 1], [2005, 1.3], [2010, 1.83]]; 

var plot = $.plot($("#placeholder"), 
     [ { data: fert, label: "Fertility"} ], { 
      series: { 
       lines: { show: true }, 
       points: { show: true } 
      }, 
      grid: { hoverable: true, clickable: true }, 
      yaxis: { min: 0, max: 2} 
     }); 

我看到的問題是什麼,我做了一個異步調用Ajax,我需要執行的jQuery之後我評價德JSON信息(OBJ = EVAL(」 (「+ json_data +」)「))但我只是不知道如何! 如果有幫助我已經使用了一個名爲「flot」的庫來完成圖形。 非常感謝!任何幫助將被預期:)

+0

爲什麼不使用'$ .ajax()'? – zerkms

+3

爲了天命,請使用'JSON.parse'而不是'eval'。 *所以*更安全。 – lonesomeday

回答

1

當前您的jQuery代碼是在文檔就緒處理程序,所以(顯然)它在文檔準備就緒後運行 - 時間與您的Ajax調用無關。相反,把你的jQuery代碼放在它自己的函數中,在你設置obj之後立即調用它。或者只是直接將jQuery代碼到您設定obj功能:

var json_data = http_request.responseText; 
    obj = eval("(" + json_data + ")"); 
    //at this point I have the information I want in "obj" 
    // either process obj directly here, or call a function to do it... 
    processData(obj); 

    ... 

    function processData(obj) { 
    // your jQuery code here, using obj 
    } 

更好不過,既然您使用jQuery反正是做阿賈克斯與one of jQuery's Ajax functions。我建議$.getJSON()

$.getJSON("yourURLhere", function(obj) { 
    // your jQuery code using obj here 
}); 
+0

非常感謝!我不是很熟悉jQuery,所以我使用了第一個選項,並完美地工作:) –

+0

不客氣。值得研究jQuery的Ajax函數,因爲我的問題末尾的代碼在一行中執行了所有'http_request'處理代碼 - jQuery處理所有'readyState'和'status'檢查您的操作... – nnnnnn

0

當您使用jQuery的AJAX調用時,您可以提供一個函數,在收到數據後執行。它甚至有一個自動分析JSON的變體,如下所示:

$.getJSON(url, options, function(response) { 
    ... do something with the data ... 
});