javascript - 如何将值存储在从 OnChange 到我的 AJAX 脚本的全局变量中?

标签 javascript jquery ajax

我正在尝试将用户在 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/

相关文章:

javascript - 浏览器后退按钮点击事件

javascript - clearTimeout 在 javascript 自动完成脚本中不起作用

javascript - 为什么jQuery显示&隐藏效果只对嵌入式css显示有效 :none?

jquery - [Rails]jQuery : Syntax error, 无法识别的表达式

php - 如何用php和mysql计算剩余时间?

c# - Ajax.BeginForm() 带有复选框语法错误

javascript - AngularJS - 使用 Mysql 进行过滤

javascript - Backbone.js ListenToOnce 被调用两次

javascript - 什么会导致 IE 报错 Object doesn't support property or method 'removeChild' ?

javascript - 服务器端处理与客户端处理+ ajax?