JavaScript和Ajax,只使用警报时有效() [英] Javascript and AJAX, only works when using alert()

查看:176
本文介绍了JavaScript和Ajax,只使用警报时有效()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的JavaScript的麻烦。这似乎是行为异常。这是怎么回事。我有一个表格,在用户提交后,它会调用一个函数(onsubmit事件)来验证所提交的数据,如果有什么不好的,或者如果用户名/电子邮件已经在数据库(使用AJAX这部分),它会返回false并使用DOM显示错误。下面是低于code。有什么奇怪的呢,就是它只有当我使用一个空警报('')的消息,如果没有它,它只是不工作的基础。感谢您的帮助。

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

功能HTT prequest(){
    VAR XMLHTTP;

    如果(window.XMLHtt prequest){
    // $ C $下IE7 +,火狐,Chrome,歌剧,Safari浏览器
    XMLHTTP =新XMLHtt prequest();
    }否则,如果(window.ActiveXObject){
    // code对IE6,IE5
    XMLHTTP =新的ActiveXObject(Microsoft.XMLHTTP);
    } 其他 {
    警报(您的浏览器不支持XMLHTTP!);
    }

    返回XMLHTTP;
}

功能validateRegForm(REG){

    VAR isValidForm = TRUE;
    VAR warningIcon =; //为以后的情况下,我们想用一个图标旁边的警示味精

    与(REG){


    变种regFormDiv =的document.getElementById(registration_form);

    //检查动态分区存在,如果有,将其删除
    如果(的document.getElementById('disp_errors')!= NULL){
    变种dispErrorsDiv =的document.getElementById('disp_errors');
    的document.getElementById('reg_form')removeChild之(dispErrorsDiv)。
    }

    //动态创建新的格
    VAR errorDiv = document.createElement方法('格');
    errorDiv.setAttribute('身份证','disp_errors');
    errorDiv.setAttribute(风格,背景颜色:粉红色;边框:1px的固体红色​​;颜色:红色;填充:10px的;');
    。的document.getElementById('reg_form')的insertBefore(errorDiv,regFormDiv);




    VAR XMLHTTP = HTT prequest();
    VAR可用=新的Array();
    xmlhttp.onreadystatechange =功能(){
    如果(xmlhttp.readyState == 4)
    {
    VAR响应= xmlhttp.responseText;
    如果(响应!=){

    //返回值
    VAR为newValue = response.split(|);
    可用的[0] =为newValue [0];
    可用的[1] =为newValue [1];
    }
    }
    }

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


    	警报(' '); ////////////不这样做,这是行不通的。为什么?

    如果(可[1] ==采取){
    errorDiv.innerHTML + = warningIcon +用户名已被使用< BR!/>';
    isValidForm = FALSE;
    }否则如果(u_username.value.length 4;){
    errorDiv.innerHTML + = warningIcon +'用户名必须超过4个字符长< BR!/>';
    isValidForm = FALSE;
    }否则如果(u_username.value.length→35){
    errorDiv.innerHTML + = warningIcon +'用户名必须少于34个字符长< BR!/>';
    isValidForm = FALSE;
    }


    如果(可用[0] ==采取){
    errorDiv.innerHTML + = warningIcon +'输入的电子邮件地址已在使用< BR!/>';
    isValidForm = FALSE;
    }否则,如果(u_email.value ==){
    errorDiv.innerHTML + = warningIcon +电子邮件地址是必需的< BR!/>';
    isValidForm = FALSE;
    	} 其他 {
    //确定是否进入电子邮件是有效的
    VAR过滤= /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0- 9] {2,4})+ $ /;
    如果(!filter.test(u_email.value)){
    errorDiv.innerHTML + = warningIcon +电子邮件输入无效< BR!/>';
    u_email.value =;
    isValidForm = FALSE;
    }
    }


    如果(u_fname.value ==){
    errorDiv.innerHTML = warningIcon +'你的名字是必需的< BR!/>';
    isValidForm = FALSE;
    }

    如果(u_lname.value ==){
    errorDiv.innerHTML + = warningIcon +你的姓是必需的< BR!/>';
    isValidForm = FALSE;
    }



    如果(u_password.value.length 4;){
    errorDiv.innerHTML + = warningIcon +密码必须超过4个字符长< BR!/>';
    isValidForm = FALSE;
    }否则如果(u_password.value.length→35){
    errorDiv.innerHTML + = warningIcon +密码必须少于34个字符长< BR!/>';
    isValidForm = FALSE;
    }否则,如果(u_password.value!= u_password2.value){
    errorDiv.innerHTML + = warningIcon +密码,然后重新输入密码,不要\'吨匹配< BR!/>';
    isValidForm = FALSE;
    }


    如果(u_squestion.value ==){
    errorDiv.innerHTML + = warningIcon +安全问题是必需的< BR!/>';
    isValidForm = FALSE;
    }

    如果(u_sanswer.value ==){
    errorDiv.innerHTML + = warningIcon +'一个安全的答案是必需的< BR!/>';
    isValidForm = FALSE;
    }

    如果(u_address.value ==){
    errorDiv.innerHTML + = warningIcon +'地址是必需的< BR!/>';
    isValidForm = FALSE;
    }

    如果(u_city.value ==){
    errorDiv.innerHTML + = warningIcon +'城市是必需的< BR!/>';
    isValidForm = FALSE;
    }

    如果(u_state.value ==){
    errorDiv.innerHTML + = warningIcon +'要求国家< BR!/>';
    isValidForm = FALSE;
    }

    如果(u_zip.value ==){
    errorDiv.innerHTML + = warningIcon +'邮编code是必需的< BR!/>';
    isValidForm = FALSE;
    }

    如果(u_phone.value ==){
    errorDiv.innerHTML + = warningIcon +电话号码是必需的< BR!/>';
    isValidForm = FALSE;
    }

    如果(isValidForm ==假)
    window.scroll(0,0);

    返回isValidForm;
    }

}
 

解决方案

警报()帮助,因为,从延迟剩余的JavaScript的处理,该函数(一切在警报()下到谷底),留出足够的时间AJAX请求完成。 Ajax中的第一个字母代表异步,这意味着(默认)的响应会在某个时候在未来,而不是马上。

一个修复(你应该的没有的实施)是使处理同步(通过改变的第三个参数的open()),将停止脚本(和整个网页)的进一步处理,直至请求返回。这是不好的,因为这将有效地冻结了Web浏览器,直至请求完成。

正确的解决方法是调整你的code,使依赖于Ajax请求的结果,任何处理进入到的onreadystatechange 功能,并能 T为在主函数初始化Ajax请求。

这是一般处理的方法是修改你的DOM(AJAX请求被发送之前),以使窗体只读,并显示了某种处理的字样,然后在Ajax响应处理程序,如果一切正常(的服务器正常响应的的验证是成功的)调用提交()的形式,否则再次进行形式wriable并显示所有的验证错误。

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.

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

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

}

解决方案

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.

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.

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.

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.

这篇关于JavaScript和Ajax,只使用警报时有效()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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