简体   繁体   English

AJAX在调试模式下有效,但不是实时的

[英]AJAX works when in debug mode but not in real time

My code works when i'm slowly stepping through in debug mode, but when i try it in real time, it doesn't seem to want to update the page. 当我逐步进入调试模式时,我的代码有效,但是当我实时尝试时,它似乎并不想更新页面。 Here is the javascript: 这是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);
  }
}

Two things you need to do 您需要做的两件事

  1. Cancel the click action that is triggering the function 取消触发该功能的点击动作
  2. Second encode the content you are sending to the server 然后对要发送到服务器的内容进行编码

Updated code: 更新的代码:

function searchItem (event){
    event.preventDefault();
    var searchStringEnc = encodeURIComponent(searchBox.value);
    ...
    xmlhttp.open("GET", "search.php?search=" + searchStringEnc, true);

It's not working on IE, rest of the responses and suggestions here are correct. 它不适用于IE,其余的回答和建议在这里都是正确的。 Why IE only? 为什么只有IE? because you have undefined vars: 因为您有未定义的变量:

searchString = searchBox.value;

correct 正确

var searchString = searchBox.value;

To check if your script is truly working just alert the formatted string. 要检查脚本是否确实有效,只需警告格式化的字符串。

article.innerHTML += string;
alert(string);

then you will know what is wrong. 那么您会知道哪里出了问题。

If you're using a button in a form to post with AJAX, make sure the button type="button" or it will act as a submit button and submit the form. 如果您使用表单中的按钮向AJAX发布,请确保按钮类型=“ button”,否则它将充当提交按钮并提交表单。 This little feature cost me days of frustration!!! 这个小功能让我感到沮丧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM