0

我正在编写一个简单的 ajax 函数:

1 function setXMLHttpRequest() {
2     var xhr = null;
3     if (window.XMLHttpRequest) {
4         xhr = new XMLHttpRequest();
5     }
6     else if (window.ActiveXObject) {
7         xhr = new ActiveXObject("Microsoft.XMLHTTP");
8     }
9     return xhr;
10 }
11
12
13 var xhrObj = setXMLHttpRequest();
14 function get_commenti(id)
15 {
16     var url = "get_commenti.php?id="+id;
17     xhrObj.open("GET", url, false);
18     xhrObj.onreadystatechange = add_commenti(id);
19     xhrObj.send(null);
20 }
21 
22 function add_commenti(id)
23 {
24     if(xhrObj.readyState == 4)
25     {
26         var id_div = "commento_"+id;
27         document.getElementById(id_div).innerHTML += xhrObj.responseText;
28     }
29     alert(xhrObj.readyState);
30 }

问题是第 29 行警告的 readystatechange 始终为 1 而从不为 4。如果我使用浏览器访问页面 <"get_commenti.php?id="+id> 它会按预期打印结果(我也尝试放置绝对路径)。

我已经尝试查找问题,但现在似乎每个人都在使用 jQuery 而我还没有。

值得注意的是,我在自己的 Web 服务器上运行它,所以可能是因为我配置了一些东西?

谢谢!

4

3 回答 3

3

您没有分配功能

xhrObj.onreadystatechange = add_commenti(id);

你正在调用它。

您需要使用闭包。

xhrObj.onreadystatechange = function() { add_commenti(id); };
于 2014-01-02T16:43:15.670 回答
1

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Properties

onreadystatechange不应与同步请求一起使用。只需在 ajax 请求之后立即使用响应

function get_commenti(id)
 {
     var url = "get_commenti.php?id="+id;
     xhrObj.open("GET", url, false);
     xhrObj.send(null);
     var id_div = "commento_"+id;
     document.getElementById(id_div).innerHTML += xhrObj.responseText;
 }
于 2014-01-02T16:41:09.250 回答
0

我用if (xhrObj.readyState == 4 && xhrObj.status == 200)try that 代替也许?

于 2014-01-02T16:39:03.223 回答