如何从JavaScript调用JQuery函数(异步调用后)

时间:2012-05-21 21:57:15

标签: javascript jquery json flot

我正在开发的代码的想法是从JSON文件(我从服务器获取)中提取数据,然后使用漂亮而漂亮的图形显示结果。问题是我无法检索我在Jquery代码中保存JSON结果的对象,因此我可以在图形中加载它们。 为简化起见,我的代码就像这样(Javascript部分)

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调用,我需要在评估de json信息后立即执行jQuery(obj = eval(“(”+ json_data +“)”))但我只是不知道怎么样! 如果它有帮助我使用了一个名为“flot”的库来做图形。 非常感谢!任何帮助都会被贬低:)

2 个答案:

答案 0 :(得分: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做Ajax。我建议$.getJSON()

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

答案 1 :(得分:0)

使用jQuery的AJAX调用时,可以提供在收到数据后执行的函数。它甚至有一个自动解析JSON的变体,如下所示:

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