[英]Ajax script calls php script twice
I use ajax on my html page to load data from MySql db wo reload and send email notification on some event, after selecting on html page - ajax calls script.php that made request to db and return result, it works perfect; 我在html页面上使用ajax从MySql db加载数据,并在某个事件上重新加载并发送电子邮件通知,在html页面上进行选择之后-ajax调用向数据库发出请求并返回结果的script.php,它运行完美; and in same time I use function that shows and hides ajax loader image until query is executed, but it calls my php script twice so that each time it sends email twice
并且在同一时间,我使用显示和隐藏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>
how to improve this code to call php script just one time? 如何改进此代码一次调用php脚本?
HTML 的HTML
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a user:</option>
<option value="1">User1</option>
<option value="2">User2</option>
</select>
</form>
<div style="display:none" id="loading">
<p><img src="../loader.gif" /></p>
</div>
<br>
<div id="txtHint"><b>User info will be listed here.</b></div>
从以下位置删除onchange事件:
<select name="users" onchange="showUser(this.value)">
What are you using showUser
for? 您将
showUser
用于什么? This seems to be enough; 这似乎足够了。
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());
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.