几秒后文本改变http.responseText,.innerHTML(Javascript,Ajax)

时间:2014-04-20 06:55:27

标签: javascript ajax

当我们尝试删除包含来自通过HTML网站显示的MYSQL数据库的产品的类别时,我使用这段代码向用户显示消息:

function  deleteCategory()
{
var http = new XMLHttpRequest();
var url = "/637415/admin/scripts/deleteCategory.php"; 
var params = "selectCatDelete=" + document.getElementById("selectedCatDelete").value;
console.log("The value is:",  params);
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.responseText == 0 && http.status == 200) {
        document.getElementById("responseText").innerHTML = "You need to delete products from the category, go to the delete products page here: <a href='/637415/admin/deleteProduct.php'>Delete produy</a>";
    }
    if(http.readyState == 4 && http.status == 200) {
        document.getElementById("responseText").innerHTML = "Category deleted";
    }

}
http.send(params);
console.log(params);

}

文字发生了变化,但几秒后就会消失。

2 个答案:

答案 0 :(得分:0)

在不知道其余代码的情况下,它可能与您拥有的location.reload()有关。一旦您重新加载页面,您使用javascript所做的任何更改都将丢失,包含您的消息。

答案 1 :(得分:0)

为什么在请求完成后不显示消息。看看是否有效:

http.onreadystatechange = function() {//Call a function when the state changes.
   //if there is a request not initialized error:

    //Request finished and response is ready
    if(http.readyState == 4 && http.status == 200) {
      if(http.responseText == 0 ) {
        document.getElementById("responseText").innerHTML = "You need to delete 
        products from the category first, go to the delete products page here: 
        <a href='/637415/admin/deleteProduct.php'>Delete Products</a>";
        }else

        location.reload(); 

        }
}