我正在尝试存储this.value用户在全局变量的eMailTxt框中写入,然后让AJAX检查用户是否存在。
将值onChange传递给ValidUser
<input type="text" name="eMailTxt" id="eMailTxt" onChange="ValidUser(this.value)" />
通过php检查数据库中是否存在值
function ValidUser(str)
{
//Want to declare a global variable here
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (xmlhttp.responseText=="false")
{
$("#eMailTxt").css({'background-color':'#fed3da','color':'red'});
$("#eMailTxt").val("[User Does Not Exist]"); //Changes text if user does not exist
//Want to store str in global variable so that in $("#eMailTxt").focus function I can store back what was written earlier
}
else
{
$("#eMailTxt").css({'background-color':'#d3fef3'});
}
}
}
xmlhttp.open("GET","loginVerify.php?q="+str,true);
xmlhttp.send();
}
答案 0 :(得分:1)
在function
之前添加此内容
等,
var myStr=''
function ValidUser(str)
{
myStr=str; //Add this for assigning previous value in myStr variable
....
此外,如果您使用ajax
,请使用$.ajax function
,
var myStr='';
function ValidUser(str)
{
myStr=str;
$.ajax({
url:'loginVerify.php',
type:'GET',
data:{q:str},
success:function(response){
$("#eMailTxt").css({'background-color':'#fed3da','color':'red'});
$("#eMailTxt").val("[User Does Not Exist]");
}
});
}
答案 1 :(得分:1)
试试这个:
var eMailTxtVal = '';
function ValidUser(str)
{
eMailTxtVal = str;
$.get("loginVerify.php?q=" + str, function(data) {
if (data == "false") {
$("#eMailTxt").css({'background-color': '#fed3da', 'color': 'red'});
$("#eMailTxt").val("[User Does Not Exist]"); //Changes text if user does not exist
}
else {
$("#eMailTxt").css({'background-color': '#d3fef3'});
}
});
}
$("#eMailTxt").focus(function() {
$(this).val(eMailTxtVal);
});
答案 2 :(得分:1)
myStr='';
ValidUser = function(str)
{
myStr= str;
}
答案 3 :(得分:0)
只需将变量声明为“高于”任何函数的范围。在更改之前设置它,然后在需要时调用它。