[英]How to call JQuery function from JavaScript (after asynchronous call)
我现在正在开发的代码的想法是从JSON文件(我从服务器获取)中提取数据,然后使用美观漂亮的图形显示结果。 问题是我无法检索将JSON结果保存在Jquery代码中的对象,因此无法将它们加载到图形中。 为简化起见,我的代码是这样的(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 info(obj = eval(“(”“ + json_data +”)“))之后需要执行jQuery,但我只是不这样做知识! 如果有帮助,我使用了一个名为“ flot”的库来制作图形。 非常感谢! 任何帮助将不胜感激:)
当前,您的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,因此可以使用jQuery的Ajax函数之一来执行Ajax 。 我建议$.getJSON()
。
$.getJSON("yourURLhere", function(obj) {
// your jQuery code using obj here
});
当您使用jQuery的AJAX调用时,可以提供一个在接收到数据后执行的功能。 它甚至具有自动解析JSON的变体,如下所示:
$.getJSON(url, options, function(response) {
... do something with the data ...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.