如何将两个ajax函数合并为一个?因此,我可以同时传递链接中的两个变量



如何将提供的两个ajax函数组合为一个?因此,我可以同时传递链接中的两个变量。我正试图通过http请求传递名字和姓氏,以便使用ajax函数从数据库中检索记录。我是ajax的新手,请指导。谢谢

代码:

<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","test3.php?fname="+str,true);
xmlhttp.send();
}
}
function showUser1(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","test3.php?lname="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<div>
<input name="fname" placeholder="Enter First Name" onChange="showUser(this.value)">
</div>

<div>
<input name="lname" placeholder="Enter Last Name" type="text" onChange="showUser1(this.value)">
</div>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>

解决方案:

<html>
<head>
<script>
//We need to pass the second variable in the function like this
function showUser(fname,lname) {
if (fname == "" || lname == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","test3.php?fname="+fname+"&lname="+lname,true);
xmlhttp.send();
}
}


</script>
</head>
<body>

<form>
//Add a new set of div tags which will consists of the two input fields. Then, add the onChange event in this div tag instead of input field tags. 

<div onChange="showUser(fname.value,lname.value)">
<div>
<input name="fname" id="fname" placeholder="Enter First Name" >
</div>

<div>
<input name="lname" id="lname" placeholder="Enter Last Name" type="text">
</div>
</div>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>

</body>
</html>

相关内容

最新更新