HTML代码
<input type="text" class="form-control input-lg" placeholder="Search1" onkeyup="showHint(this.value)">
<input type="text" class="form-control input-lg" placeholder="Search2" onkeyup="showHint(this.value)">
脚本
function showHint(str) {
if (str.length == 0) {
document.getElementById("Hint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("Hint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?value=" + str, true);
xmlhttp.send();
}
}
此代码适用于单个 <input>
.但是,我需要将两个输入值传递给 JavaScript 函数并将两个值发送到 gethint.php
喜欢:
function showHint(str,str1)
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("Hint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?value=" + str+ "&ids=" +str1, true);
xmlhttp.send();
}
我这样试过,但无法解决。
最佳答案
只需从函数的输入字段中获取值,而不是将它们传递给它。为此,您应该将 ID 添加到输入字段:
function showHint(str, str1) {
// if no values are passed, get the data from the elements
if (!str) str = document.getElementById("input1").value;
if (!str1) str1 = document.getElementById("input2").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("Hint").innerHTML = this.responseText;
} else {console.log(this.status);}
};
xmlhttp.open("GET", "gethint.php?value=" + str+ "&ids=" +str1, true);
xmlhttp.send();
}
<input id="input1" type="text" class="form-control input-lg" placeholder="Search1" onkeyup="showHint()">
<input id="input2" type="text" class="form-control input-lg" placeholder="Search2" onkeyup="showHint()">
有了这个,您仍然可以使用自定义字符串调用该函数
关于javascript - AJAX 实时搜索 - 向 PHP 发送多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50316046/