Javascript Ajax脚本调用php脚本两次

Javascript Ajax脚本调用php脚本两次,javascript,jquery,ajax,Javascript,Jquery,Ajax,我在html页面上使用ajax从MySql db w.o加载数据。重新加载并发送一些事件的电子邮件通知,在html页面上选择向db发出请求并返回结果的-ajax calls script.php后,它工作得非常好;同时,我使用一个函数来显示和隐藏ajax加载器图像,直到执行查询为止,但它会调用我的php脚本两次,以便每次发送两次电子邮件 <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.js"></script

我在html页面上使用ajax从MySql db w.o加载数据。重新加载并发送一些事件的电子邮件通知,在html页面上选择向db发出请求并返回结果的-ajax calls script.php后,它工作得非常好;同时,我使用一个函数来显示和隐藏ajax加载器图像,直到执行查询为止,但它会调用我的php脚本两次,以便每次发送两次电子邮件

<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.js"></script>

<script>
function showUser(str)
{
    if (str=="")
    {
        document.getElementById("txtHint").innerHTML="";
        return;
    }
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","../getuser.php?q="+str,true);
    xmlhttp.send();
}

// ajax loader image

function getuser(str){
    $.ajax({
        url: "http://site.com/getuser.php?q="+str,
        beforeSend: function (XMLHttpRequest)
        {
            $("#loading").show();
        }
    })
    .done(function ( data ) {
        $("#txtHint").html(data);
        $("#loading").hide();
    });
}
$(document).ready(function(){
    $("select[name='users']").change(function () {
        getuser($("option:selected", this).val());
    });
});
</script>
如何改进这段代码,只调用一次php脚本

HTML

您使用showUser的目的是什么?这似乎足够了

function getuser(str) {
  $.ajax({
    url: "/getuser.php?q=" + str, // No need to include the domain here
    beforeSend: function (jqXHR) {
       $("#loading").show();
    }
  }).done(function(data) {
    $("#txtHint").html(data);
    $("#loading").hide();
  });
}

$(document).ready(function() {
  $("select[name='users']").change(function() {
    getuser($(this).val());
  });
});

从以下位置删除onchange事件:

<select name="users" onchange="showUser(this.value)"> 

在哪里调用showUser?看起来是多余的?你确定它没有被调用吗?这将有助于解释程序流程-看起来你在页面加载后调用getuser,这反过来调用getuser.php,但你调用showUser吗?更改问题,在html页面上选择后的问题开头的解释-ajax调用script.php向db发出请求并返回结果
<select name="users" onchange="showUser(this.value)">