使用 Ajax 调用从函数返回值 [英] Return value from function with an Ajax call

查看:30
本文介绍了使用 Ajax 调用从函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我如何返回status的值作为函数的返回值.

Can someone tell me how to return the value of status as the function's return value.

function checkUser() {
    var request;
    var status = false;

    //create xmlhttprequest object here [called request]

    var stu_id = document.getElementById("stu_id").value;
    var dName = document.getElementById("dName").value;
    var fileName = "check_user.php?dName=" + dName + "&stu_id=" + stu_id;
    request.open("GET", fileName, true);
    request.send(null);

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var resp = parseInt(request.responseText, 10);
            if(resp === 1) {
                alert("The display name has already been taken.");
                status = false;
            }
            else if(resp === 2) {
                alert("This student ID has already been registered");
                status = false;
            }
            else if(resp === 0) {
                status = true;
            }
        }
    }
    return status;
}

当您在注册表单中点击提交时会触发上述功能(必须很明显).问题是,无论响应是什么,此表单都会提交,并且警告框有时不显示任何内容 [空白],有时根本不显示.但是,如果我手动将结束 status 更改为 false [即将 status 替换为 false],警报框中会显示正确的值.

The above function triggers when you hit submit in a registration form (as must be obvious). The problem is, this form submits irrespective of what the response is, and the alert box sometimes shows nothing [blank], sometimes doesn't show at all. However, if I change the ending status to false manually [i.e. replace status with false], the correct value shows up in the alert box.

附言我在 javascript 方面比菜鸟还差,所以也欢迎提出总体改进代码的建议.

P.S. I'm worse than a noob in javascript, so suggestions on generally improving the code is also welcome.

推荐答案

问题是 onreadystatechange 不会触发直到...等待它...状态改变.所以当你 return status; 大部分时间状态不会有时间设置.您需要做的是 return false; 始终并在 onreadystatechange 内确定您是否要继续.如果你这样做,那么你提交表格.简而言之,使用处理返回值的代码,而是从 readystatechange 处理程序中运行它.您可以直接执行此操作:

The problem is that onreadystatechange won't fire until... wait for it... the state changes. So when you return status; most of the time status will not have had time to set. What you need to do is return false; always and inside the onreadystatechange determine whether you want to proceed or not. If you do, then you submit the form. In short, take the code that handles the return value and instead run it from within the readystatechange handler. You can do this directly:

request.onreadystatechange = function() {
    if (request.readyState == 4) {
        var resp = parseInt(request.responseText, 10);
        switch (resp) {
        case 0:
            document.getElementById('myform').submit();
            break;
        case 1:
            alert("The display name has already been taken.");
            break;
        case 2:
            alert("This student ID has already been registered");
            break;
        }
    }
}
return false; // always return false initially

或通过传递 continuation到进行异步调用的函数:

or by passing a continuation to the function that makes the asynchronous call:

function checkUser(success, fail) {
    ...
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var resp = parseInt(request.responseText, 10);
            switch (resp) {
            case 0:
                success(request.responseText);
            case 1:
                fail("The display name has already been taken.", request.reponseText);
                break;
            case 2:
                fail("This student ID has already been registered", request.reponseText);
                break;
            default:
                fail("Unrecognized resonse: "+resp, request.reponseText);
                break;
            }
        }
    }

除此之外,在默认 return false; 之前,您可能想要某种指示正在发生的事情,也许禁用提交字段,显示加载圆圈等.否则如果获取数据需要很长时间,用户可能会感到困惑.

In addition to this, before the default return false; you might want to have some sort of indicator that something is going on, perhaps disable the submit field, show a loading circle, etc. Otherwise users might get confused if it is taking a long time to fetch the data.

好吧,所以你的方法不起作用的原因主要是在这一行:

Alright, so the reason your way didn't work is mostly in this line:

request.onreadystatechange = function() {

那是说当 AJAX 请求的 onreadystatechange 发生变化时,您定义的匿名函数将运行.此代码不会立即执行.它正在等待事件发生.这是一个异步过程,所以在函数定义的最后,javascript 将继续运行,如果状态在它到达 return status; 变量 status 显然没有时间设置,您的脚本将无法按预期工作.在这种情况下的解决方案是总是 return false; 然后当事件触发时(即,服务器用 PHP 的脚本输出响应)然后您可以确定状态并提交表单,如果一切正常-好的.

What that is doing is saying that when the onreadystatechange of the AJAX request changes, the anonymous function you are defining will run. This code is NOT being executed right away. It is waiting for an event to happen. This is an asynchronous process, so at the end of the function definition javascript will keep going, and if the state has not changed by the time it gets to return status; the variable status will obviously not have had time to set and your script would not work as expected. The solution in this case is to always return false; and then when the event fires (ie, the server responded with the PHP's script output) you can then determine the status and submit the form if everything is a-ok.

这篇关于使用 Ajax 调用从函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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