等待jQuery的$。获得正常运行code前完成 [英] Wait for jQuery $.get function to finish before running code

查看:173
本文介绍了等待jQuery的$。获得正常运行code前完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面,正在执行返回语句之前调用 $。获得()结束。我怎样才能改变呢?

VAR船尾= {}; aft.getToken =功能(URL){     VAR theToken;     //获取令牌值     $获得(URL,功能(数据){         theToken = $(数据).find('输入[名称= __ RequestVerificationToken])VAL()。     },HTML);     返回theToken; };

解决方案

您不能 - 至少不理智。虽然有一个异步属性,你可以在jQuery的Ajax请求设置,我有严重的问题试图将其与值了过去。

尝试重新思考你要完成的任务:

  VAR船尾= {yourToken:''};

aft.setToken =功能(URL,回调){
    $获得(URL,功能(数据){
        this.yourToken = $(数据).find('输入[名称= __ RequestVerificationToken])VAL()。

        如果(回调)
           callback.apply(这一点);
    },HTML);
};
 

然后:

  aft.setToken(url.php,函数(){
   警报(令牌检索=+ this.yourToken);
});
 

或者,如果你的回调的只有的需要访问返回的数据,那么你就可以更简单地做

 如果(回调)
    回调(数据);
 

然后

  aft.setToken(url.php功能(dataReturned){
   警报(阿贾克斯数据检索=+ dataReturned);
});
 

In the following, the return statement is being executed before the call to $.get() finishes. How can I change this?

var aft = {};

aft.getToken = function (url) {

    var theToken;

    //Get the token value
    $.get(url, function (data) {

        theToken = $(data).find('input[name=__RequestVerificationToken]').val();

    }, "html");

    return theToken;

};

解决方案

You can't—at least not sensibly. While there is an async property you can set on jQuery ajax requests, I've had serious problems trying to use it with a false value in the past.

Try to re-think what you're trying to accomplish:

var aft = { yourToken: '' };

aft.setToken = function (url, callback) {
    $.get(url, function (data) {
        this.yourToken = $(data).find('input[name=__RequestVerificationToken]').val();

        if (callback)
           callback.apply(this);
    }, "html");
};

And then:

aft.setToken("url.php", function() {
   alert("Token retrieved = " + this.yourToken);
});

Or, if your callback only needs access to the returned data, then you could more simply do

if (callback)
    callback(data);

And then

aft.setToken("url.php", function(dataReturned) {
   alert("Ajax data retrieved = " + dataReturned);
});

这篇关于等待jQuery的$。获得正常运行code前完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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