I am having trouble with my javascript. It seems to be acting oddly. This is what's going on. I have a form, after the user submits it, it calls a function(onsubmit event) to verify the submitted data, if something bad OR if the username/email is already in database(using ajax for this part) it'll return false and display errors using DOM. Here's the code below. What's weird about it, is that it only works when I use an empty alert('') message, without it, it just doesn't work. Thanks for the help.

我的javascript出现问题。这看起来很奇怪。这是正在发生的事情。我有一个表单,在用户提交之后,它调用一个函数(onsubmit事件)来验证提交的数据,如果有什么不好或者如果用户名/电子邮件已经在数据库中(使用此部分的ajax)它将返回false并使用DOM显示错误。这是下面的代码。有什么奇怪的,它只有在我使用空警报('')消息时才有效,没有它,它就行不通。谢谢您的帮助。

//////////////////////////////////////

function httpRequest() {
    var xmlhttp;

    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert("Your browser does not support XMLHTTP!");
    }

    return xmlhttp;
}

function validateRegForm(reg) {

    var isValidForm = true;
    var warningIcon = "";//for later in case we want to use an icon next to warning msg

    with(reg) {


        var regFormDiv = document.getElementById("registration_form");

        //Check if dynamic div exist, if so, remove it
        if(document.getElementById('disp_errors') != null) {
            var dispErrorsDiv = document.getElementById('disp_errors');
            document.getElementById('reg_form').removeChild(dispErrorsDiv);
        }           

        //Dynamically create new 'div'
        var errorDiv = document.createElement('div');
        errorDiv.setAttribute('id','disp_errors');
        errorDiv.setAttribute('style','background-color:pink;border:1px solid red;color:red;padding:10px;');
        document.getElementById('reg_form').insertBefore(errorDiv,regFormDiv);




        var xmlhttp = httpRequest();
        var available = new Array();
        xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState == 4)
            {   
                var response = xmlhttp.responseText;
                if(response != "") {

                    //Return values
                    var newValue = response.split("|");
                    available[0] = newValue[0]; 
                    available[1] = newValue[1]; 
                }
            }
        }

        xmlhttp.open("GET","profile_fetch_reg_info.php?do=available&un="+u_username.value+"&email="+u_email.value+"",true);
        xmlhttp.send(null);


        alert(' '); ////////////WITHOUT THIS, IT DOESN'T WORK. Why?

        if(available[1] == "taken") {
            errorDiv.innerHTML += warningIcon+'Username is already taken!<br />';
            isValidForm = false;
        } else if(u_username.value.length < 4){
            errorDiv.innerHTML += warningIcon+'Username must be more than 4 characters long!<br />';
            isValidForm = false;
        } else if(u_username.value.length > 35) {
            errorDiv.innerHTML += warningIcon+'Username must be less than 34 characters long!<br />';
            isValidForm = false;
        }


        if(available[0] == "taken") {
            errorDiv.innerHTML += warningIcon+'Email address entered is already in use!<br />';
            isValidForm = false;
        } else if(u_email.value == ""){
            errorDiv.innerHTML += warningIcon+'Email address is required!<br />';
            isValidForm = false;
        } else {
            //Determine if email entered is valid
            var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if (!filter.test(u_email.value)) {
                errorDiv.innerHTML += warningIcon+'Email entered is invalid!<br />';
                u_email.value = "";
                isValidForm = false;
            }
        }


        if(u_fname.value == ""){
            errorDiv.innerHTML = warningIcon+'Your first name is required!<br />';
            isValidForm = false;
        }

        if(u_lname.value == ""){
            errorDiv.innerHTML += warningIcon+'Your last name is required!<br />';
            isValidForm = false;
        }



        if(u_password.value.length < 4){
            errorDiv.innerHTML += warningIcon+'Password must be more than 4 characters long!<br />';
            isValidForm = false;
        } else if(u_password.value.length > 35) {
            errorDiv.innerHTML += warningIcon+'Password must be less than 34 characters long!<br />';
            isValidForm = false;
        } else if (u_password.value != u_password2.value) {
            errorDiv.innerHTML += warningIcon+'Password and re-typed password don\'t match!<br />';
            isValidForm = false;
        }


        if(u_squestion.value == ""){
            errorDiv.innerHTML += warningIcon+'A security question is required!<br />';
            isValidForm = false;
        }

        if(u_sanswer.value == ""){
            errorDiv.innerHTML += warningIcon+'A security answer is required!<br />';
            isValidForm = false;
        }

        if(u_address.value == ""){
            errorDiv.innerHTML += warningIcon+'Address is required!<br />';
            isValidForm = false;
        }

        if(u_city.value == ""){
            errorDiv.innerHTML += warningIcon+'City is required!<br />';
            isValidForm = false;
        }

        if(u_state.value == ""){
            errorDiv.innerHTML += warningIcon+'State is required!<br />';
            isValidForm = false;
        }

        if(u_zip.value == ""){
            errorDiv.innerHTML += warningIcon+'Zip code is required!<br />';
            isValidForm = false;
        }

        if(u_phone.value == ""){
            errorDiv.innerHTML += warningIcon+'Phone number is required!<br />';
            isValidForm = false;
        }

        if(isValidForm == false)
            window.scroll(0,0);

        return isValidForm;
    }

}

9 个解决方案

#1


11

The alert() helps because that delays the processing of the remaining javascript in that function (everything from the alert() down to the bottom), leaving enough time for the AJAX request to complete. The first letter in AJAX stands for "asynchronous" which means that (by default) the response will come in at "some point in the future" but not immediately.

alert()有帮助,因为它延迟了该函数中剩余javascript的处理(从alert()到底部的所有内容),留下足够的时间来完成AJAX请求。 AJAX中的第一个字母代表“异步”,这意味着(默认情况下)响应将在“未来的某个点”进入,但不会立即进行。

One fix (which you should not implement) is to make the processing synchronous (by changing the third argument of open() to be false) which will stop further processing of your script (and the entire webpage) until the request returns. This is bad because it will effectively freeze the web browser until the request completes.

一个修复(你不应该实现)是使处理同步(通过将open()的第三个参数更改为false),这将停止进一步处理脚本(和整个网页),直到请求返回。这很糟糕,因为它会有效地冻结Web浏览器,直到请求完成。

The proper fix is to restructure your code so that any processing that depends on the result of the AJAX request goes in to the onreadystatechange function, and can't be in the main function that initiates the AJAX request.

正确的解决方法是重构代码,以便依赖于AJAX请求结果的任何处理都进入onreadystatechange函数,并且不能在启动AJAX请求的main函数中。

The way this is usually handled is to modify your DOM (before the AJAX request is sent) to make the form readonly and display some sort of "processing" message, then in the AJAX response handler, if everything is okay (the server responded properly and validation was successful) call submit() on the form, otherwise make the form wriable again and display any validation errors.

通常处理的方法是修改你的DOM(在发送AJAX请求之前)使表单只读并显示某种“处理”消息,然后在AJAX响应处理程序中,如果一切正常(服务器响应正常)并且验证成功)在表单上调用submit(),否则使表单再次变为可用并显示任何验证错误。

更多相关文章

  1. javaES6箭头函数的全新特性
  2. JavaScript学习-5——异步同步、回调函数
  3. Javascript实现统一的表单验证
  4. 什么“返回此”在javascript函数中做什么?
  5. jQuery和AJAX - 使用Ajax添加的对象动态不适用于jQuery函数?
  6. 【JavaScript】案例一:使用JS完成注册页面表单校验
  7. Javascript偏函数与柯里化
  8. 如何检查不包含提交按钮的HTML5表单的有效性?
  9. 当函数在单独的PHP文件中定义时,调用JavaScript函数onclick按钮事

随机推荐

  1. 在android里面使用自定义字体
  2. MIPS android 编译总结
  3. Android数据与服务器交互的GET,POST,HTTP
  4. APIDEMO 字体默认样式
  5. Android(安卓)SMS(二)—— 读取短信保存到
  6. Android屏幕分辨率
  7. Android按键消息传播流程(WindowManagerSe
  8. android 笔记 --- Android中Menu应用
  9. OrmLite - Lightweight Java ORM Support
  10. TextView的跑马灯效果