为什么此jQuery函数无法正常运行? [英] Why won't this jQuery function perform properly?

查看:120
本文介绍了为什么此jQuery函数无法正常运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当涉及到jQuery时,我是一个菜鸟,但我正在尝试学习.我在这里做错什么了?

I'm a total noob when it comes to jQuery but I am trying to learn. What in tarnation am I doing wrong here?

function MakeCall(url) { 
var result;
$.ajax({
    url: url,
    dataType: "text",
    success: function(txt) {
        result = txt;
        return;
    }
});
alert(result);
return result;
}

好的,对那点愚蠢的事感到抱歉...我已经修复了那部分.现在我的问题是,即使在成功函数中正确设置了结果,警报现在所处的位置也将返回未定义".

ok, sorry about that bit of stupidity... i've fixed that part. now my problem is that the alert where it is now is returning "undefined", even though the result is getting set properly in the success function...

非常感谢...

推荐答案

道歉-我正在交叉发布该问题的答案,只看到了此人最初发布的其他问题.

Apologies - I'm cross posting an answer to the question, only saw the other question this guy posted originally.

jQuery的ajax函数是异步的-因此,成功函数将在第二个警报运行后被称为 .然后它将在ajax方法完成之前从函数返回.

Jquery's ajax functions are asynchronous - therefore the success function will be called after the second alert is run. It will then return from the function before the ajax method is completed.

如果您真的想以这种方式构建应用程序,则可以在调用中添加 async 选项,并将其设置为false. ( http://docs.jquery.com/Ajax/jQuery.ajax#options,请参阅第一个条目.)这将导致在$ .ajax方法返回之前调用成功函数.

If you really want to build the app this way, you can add an async option to the call, setting it to false. (http://docs.jquery.com/Ajax/jQuery.ajax#options, see the first entry.) This will result in the success function being called before the $.ajax method returns.

但是,不建议阻塞ajax调用,因为这会挂起脚本和浏览器.

However, doing blocking ajax calls is not recommended, as it will hang the script and the browser.

因此,我建议您按照以下方式重组应用程序:

Therefore, I advise you to restructure the application as such:

function MakeCall(url, callback) { 

$.ajax({
    url: url,
    dataType: "text",
    success: callback
});

}

MakeCall('http://theurl.com', function(txt) {
        result = txt;
        alert(result);
        return;
});

这篇关于为什么此jQuery函数无法正常运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆