我正在尝试将用户在 eMailTxt 框中写入的 this.value 存储在一个全局变量中,然后让 AJAX 来检查用户是否存在。
HTML
将值 onChange 传递给 ValidUser
<input type="text" name="eMailTxt" id="eMailTxt" onChange="ValidUser(this.value)" />
AJAX##
通过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();
}
最佳答案
在你的函数
之前添加这个
喜欢,
var myStr=''
function ValidUser(str)
{
myStr=str; //Add this for assigning previous value in myStr variable
....
此外,如果您使用的是 ajax
,则为此使用 $.ajax 函数
,
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]");
}
});
}
关于javascript - 如何将值存储在从 OnChange 到我的 AJAX 脚本的全局变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17481146/