我尝试创建AJAX函数,但它在输出中显示了注释
var ajaxObj = function(url, meth, data = "") {
var x = new XMLHttpRequest();
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
this.responseAjax = this.responseText;
}
}
x.open(meth, url, true);
x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
x.send(data);
}
function showHint(str) {
var xhttp = new ajaxObj("gethint.php?q=" + str, "GET");
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
document.getElementById("txtHint").innerHTML = xhttp.responseAjax;
}

<!DOCTYPE html>
<html>
<body>
<h3> Start typing a name in the input field below :</h3>
<form action="">
First Name : <input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>
<p>Suggestions:
<sapn id="txtHint"></sapn>
</p>
</body>
</html>
&#13;
当用户开始在文本框中输入时,我尝试从gethint.php文件中获取建议的名称。 但似乎responseAjax在showHint()调用之后得到了值,请帮助我。
答案 0 :(得分:0)
this
处理程序中的 onreadystatechange
是XMLHttpRequest
的实例,因此行this.responseAjax = this.responseText
正在向XMLHttpRequest
对象添加字段并设置其值到同一个对象的另一个字段。这完全是多余的。在showHint
中,xhttp
是ajaxObj
的一个实例,并且没有为此对象定义responseAjax
字段。您可以直接在innerHTML
的处理程序中设置显示建议的元素onreadystatechange
,如下所示:
function getSuggestions (meth, data) {
meth = meth.toUpperCase();
var params = "q=" + data;
var url = (meth == "GET") ? "gethint.php?" + params : "gethint.php";
var elem = document.getElementById("txtHint");
if (data.length == 0) {
elem.innerHTML = "";
return;
}
var x = new XMLHttpRequest();
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
elem.innerHTML = this.responseText;
}
}
x.open(meth, url, true);
x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if (meth == "GET") {
x.send();
} else {
x.send(params);
}
}
和showHint
变为:
function showHint(str) {
getSuggestions ("GET", str);
}
答案 1 :(得分:0)
您需要异步处理AJAX请求。在致电
时的showHint
功能中
document.getElementById("txtHint").innerHTML = xhttp.responseAjax;
AJAX调用尚未返回,因此尚未定义xhttp.responseAjax对象。一旦到达,您需要等待处理响应。您可以将回调函数传递给ajaxObj
定义,并且对象将在获得响应时调用该函数。
var ajaxObj = function(url, meth, callback, data = "") {
var x = new XMLHttpRequest();
x.onreadystatechange = function() {
if (x.readyState == 4 && x.status == 200) {
// we're ready to handle the response data now
callback(x.responseText);
}
}
x.open(meth, url, true);
x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
x.send(data);
}
// Callback function to be invoked when AJAX is complete
function fillTxtHint(responseHtml)
{
document.getElementById("txtHint").innerHTML = responseHtml;
}
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
}
// Pass in the callback function to be invoked when AJAX has returned
ajaxObj("gethint.php?q=" + str, "GET", fillTxtHint);
}