简体   繁体   English

用Javascript函数调用jQuery函数

[英]Calling jQuery Function with Javascript Function

Having some trouble getting this to work, specifically with $.getJSON(). 使此功能无法正常工作,特别是在$ .getJSON()中。 I want to wrap the getJSON function from jQuery in a Javascript function like so: 我想将jQuery中的getJSON函数包装在Javascript函数中,如下所示:

function reload_data() {
    $.getJSON("data/source", function(data) {
        $.d = data;
    });
}

But when I call reload_data() it doesn't execute the jQuery function inside. 但是当我调用reload_data()时,它不执行内部的jQuery函数。 Any ideas? 有任何想法吗?

You're not telling us enough. 你告诉我们的还不够。 I will just take a guess! 我只是猜测一下!

If you are calling this function, and then immediately checking $.d for the results, that is not going to work because you don't allow time for the asynchronous AJAX request to complete... 如果要调用此函数,然后立即检查$ .d的结果,那将是行不通的,因为您没有时间让异步 AJAX请求完成...

reload_data();
alert($.d); // What?!  It's not displaying the updated results?!

You'll have to utilize a callback structure, like jQuery uses, in order to make it work... 您必须像jQuery一样使用回调结构,以使其工作...

reload_data(function() {
  alert($.d);
});

function reload_data(func) {
  $.getJSON("data/source", function(data) {
    $.d = data;
    //Execute the callback, now that this functions job is done
    if(func)
      func();
  });
}

Put an Alert in side the function to know its getting called. 将Alert放在函数旁边以知道其被调用。

and a try catch around the jQuery call to see if there is an error 然后尝试赶上jQuery调用以查看是否存在错误

function reload_data() {
    alert('reload_data  start');
    try{
        $.getJSON("data/source", function(data) {
            $.d = data;
        });
     }
     catch (ex){
         alert ('error in jQuery call:' + ex)
     }
}

Thanks for the help everyone, but the solution was actually really simple. 感谢大家的帮助,但是解决方案实际上非常简单。 It was just a matter of synchronization. 这只是同步问题。 The page was reloading before the JSON data got reloaded, so that's why I wasn't seeing an error. 在重新加载JSON数据之前已重新加载页面,所以这就是为什么我没有看到错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM