Ajax请求成功但响应为null但我可以在firebug中看到结果响应:
<?xml version="1.0" encoding="UTF-8" ?><response><likes>13</likes></response>
在控制台中出现错误:
TypeError:响应为空
var XMLHttpObject = createXMLHttpRequest();
$Id = null;
function process(id) { //makeAsynchornusRequest
if(XMLHttpObject.readyState == 0 || XMLHttpObject.readyState == 4) {
XMLHttpObject.onreadystatechange = responseHandler;
$Id = id;
XMLHttpObject.open("GET","like/" + id);
XMLHttpObject.send(null);
}
}
function responseHandler() {
if(XMLHttpObject.readyState == 4) {
if(XMLHttpObject.status == 200) { // 200 implies `ok` like 400 implies `page not found`
response = XMLHttpObject.responseXML;
xmlDocumentElement = response.documentElement;
output = document.getElementById("num_likes" + $Id);
output.innerHTML = xmlDocumentElement ;
}
}
}
答案 0 :(得分:0)
您已经标记了JQuery - 尝试使用JQuery进行Ajax调用:
$.ajax({
url: '/Likes',
data: { id: id },
success: function (response) {
if (response) {
console.log(response);
}
},
error: function (xhr, s, sa) {
console.log(s, sa);
},
complete: function () {
console.log('complete event');
}
});
答案 1 :(得分:0)
您可以尝试将其切换为onLoad
事件处理程序。
来自mozilla docs:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);
// If specified, responseType must be empty string or "document"
xhr.responseType = 'document';
// overrideMimeType() can be used to force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response);
console.log(xhr.responseXML);
}
}
};
xhr.send(null);
使用您的代码(请注意,您可能需要略微调整responseHandler()
正文:
XMLHttpObject.open("GET","like/" + id);
xhr.onload = responseHandler;
XMLHttpObject.send(null);