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

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

问题描述

有人可以告诉我如何返回状态值作为函数的返回值。

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;
}

以上功能触发,当你点击提交登记表(如必须是显而易见的)。问题是,这种形式提交无关的反应是什么,并警告框有时显示什么[空白],有时不显示在所有。不过,如果我更改状态结束手动[即替换状态],正确的值显示在提示框。

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.

P.S。我比在JavaScript中小白差,所以建议在普遍提高了code也是欢迎的。

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

推荐答案

问题是,的onreadystatechange 将不会触发直到...等待它...的状态的变化。所以,当你返回状态; 大部分时间状态将不会有足够的时间来设置。你需要做的是返回false; 总是和内部的的onreadystatechange 确定是否要继续或取消。如果你这样做,那么你提交表单。总之,采取code处理的返回值,而不是从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

或传递一个延续的功能,使异步调用:

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;
            }
        }
    }

除此之外,默认的前返回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() {

那是什么做的是说,当的onreadystatechange 的AJAX请求更改,您所定义的匿名函数将运行。这code没有被立即执行。它在等待一个事件的发生。这是一个异步的过程,所以在函数定义结束的JavaScript会继续下去,而且如果国家还没有通过它到达返回状态的时候改变; 变量状态显然不会有时间来设置,并如预期你的脚本是行不通的。在这种情况下,解决的办法是要始终返回false; ,然后当事件触发时(即,在服务器上使用PHP的脚本输出响应),那么你可以决定自己的状态,并提交如果一切都OK的形式。

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天全站免登陆