![](/img/trans.png)
[英]Ajax call works in IE and Chrome (and only in Firefox when adding breakpoint in debug mode at end of ajax call)
[英]AJAX works when in debug mode but not in real time
当我逐步进入调试模式时,我的代码有效,但是当我实时尝试时,它似乎并不想更新页面。 这是JavaScript:
searchButton = document.getElementById("searchButton");
var searchBox = document.getElementById('searchBox');
searchButton.addEventListener("click", searchItem);
function searchItem(){
searchString = searchBox.value;
article = document.getElementById("homeSection");
var xmlhttp = getXmlHttpRequestObject();
var string = '';
if(xmlhttp){
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var response = JSON.parse(xmlhttp.responseText);
for(var i=0; i<response.length; i++){
string += '<section class="searchResult">';
string += '<h1>' + response[i].Name + '</h1>';
string += '<p class="photo"></p>';
string += '<p class="price">£' + response[i].Price + '</p>';
string += '<p class="productID">ID: ' + response[i].ID + '</p>';
string += '<p class="description">' + response[i].Description + '</p>';
string += '<p class="quantity">Quantity: ' + response[i].Quantity + '</p>';
string += '</section>';
}
article.innerHTML = '<h1>Search</h1><section><h1 class="bottomBorder">You searched for: "' + searchString + '"</h1></section>';
article.innerHTML += string;
}
};
xmlhttp.open("GET", "search.php?search=" + searchString, true);
xmlhttp.send(null);
}
}
您需要做的两件事
更新的代码:
function searchItem (event){
event.preventDefault();
var searchStringEnc = encodeURIComponent(searchBox.value);
...
xmlhttp.open("GET", "search.php?search=" + searchStringEnc, true);
它不适用于IE,其余的回答和建议在这里都是正确的。 为什么只有IE? 因为您有未定义的变量:
searchString = searchBox.value;
正确
var searchString = searchBox.value;
要检查脚本是否确实有效,只需警告格式化的字符串。
article.innerHTML += string;
alert(string);
那么您会知道哪里出了问题。
如果您使用表单中的按钮向AJAX发布,请确保按钮类型=“ button”,否则它将充当提交按钮并提交表单。 这个小功能让我感到沮丧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.