Ajax加载器脚本调用php脚本两次

时间:2013-02-18 12:08:51

标签: javascript jquery ajax

我在html页面上使用ajax从db w.o加载数据。重新加载并发送有关某些事件的电子邮件通知,其工作完美 同时我使用显示和隐藏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脚本?

1 个答案:

答案 0 :(得分:0)

  function getuser(str){
 $.ajax({
  url: "http://site.com/script.php?q="+str,
  beforeSend: function (XMLHttpRequest)
  {
     $("#loading").show();
  }
}).done(function ( data ) {
 //     $("#txtHint").html(data);
 $("#loading").hide(); });
}
$(document).ready(function(){
$("select[name='users']").bind('change',function () {
 getuser($("option:selected", this).val()); });
 });