“等待"在返回值之前将ReadyState设置为4 [英] "Waiting" for ReadyState to be 4 before returning a value

查看:183
本文介绍了“等待"在返回值之前将ReadyState设置为4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为此我在很多地方寻找过,我可能是个白痴,因为这样做很多,但这是我的情况.

I have looked in lots of places for this, and I'm probably being an idiot because this is done a lot, but here's my situation.

我试图在我的网站上的电子邮件字段旁边显示一个复选框,前提是该电子邮件尚未用于注册.

I am trying to display a checkbox next to an e-mail field on my website iff the e-mail has not been used to register already.

我所拥有的是这样的:

$('[name=reg_email]').change( function() { 
    if(!emailUsed()) {
        //Update image to be a green checkmark
    } else {
        //Update image to be a huge red X
    }
}

并且我的"emailUsed"函数应该根据电子邮件地址是否在数据库中来返回一个Javascript布尔变量.为方便起见,我创建了一个脚本来确定它是否存在.所以emailUsed()函数只需要调用脚本并返回,但是我需要等到readystate == 4之后再返回,而我发现所有等待readystate等于4的方法都会阻止我返回值完全没有:

And my "emailUsed" function should be returning a Javascript boolean variable depending on whether or not the e-mail address is in the database. To facilitate this, I've created a script which will determine if it's there or not. So the emailUsed() function just needs to call the script and return, but I need to wait until readystate == 4 before I return, and all of the methods I have found for waiting for readystate to equal 4 prevent me from returning a value at all:

function emailUsed() {
    var req = $.get('scripts/email_used.php?email='+$('[name=reg_email]').val());

    //Wait for req.readystate to be 4

    return req.responseText == 'True';
}

但是我无处可以找到解释该操作方法并仍然返回值的内容.一切似乎都在使用回调函数,但我无法使用THIS方法返回值.

But nowhere can I find something that explains how to do this and still return a value. Everything seems to use callback functions and this and that, but I can't get THIS method to return a value.

请帮助!

推荐答案

忙于等待req.readyState === 4被认为是不良的设计实践.您正在捆绑UI线程并阻止浏览器更新.如果服务器足够慢,无法响应,则将提示用户是否取消进一步的处理.

Doing a busy wait for req.readyState === 4 is considered bad design practice. You're tying up the UI thread and preventing the browser from updating. If the server is slow enough to respond, the user will get prompted whether to cancel further processing.

如果查看$ .get(),它将完成函数作为其参数之一.您应该在此功能中执行成功/失败逻辑.您可以通过禁用提交"按钮来完成此操作,直到获得成功消息为止.

If you take a look at $.get(), it takes a completion function as one of its arguments. You should perform your success/failure logic in this function. You can do this by disabling your Submit button until you get back a success message.

这篇关于“等待"在返回值之前将ReadyState设置为4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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