【发布时间】:2010-11-04 01:21:16
【问题描述】:
在发出 AJAX 请求和处理响应时,我遇到了一些奇怪的问题。
我正在对 xml 文件进行 ajax 调用。但是,当我得到响应时,xhr.responseText 属性在 Firefox 中可以正常工作,但在 IE 中却不行。 另一件事是我试图将 xhr.responseXML 作为 XMLDocument 访问,但它告诉我在 Firefox 中它告诉我 xhr.responseXML 是未定义的,即它甚至没有向我显示未定义的错误或显示输出。
这是我用来发出请求的代码:
var ajaxReq = function(url, callback) {
//initialize the xhr object and settings
var xhr = window.ActiveXObject ?
new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(),
//set the successful connection function
httpSuccess = function(xhr) {
try {
// IE error sometimes returns 1223 when it should be 204
// so treat it as success, see XMLHTTPRequest #1450
// this code is taken from the jQuery library with some modification.
return !xhr.status && xhr.status == 0 ||
(xhr.status >= 200 && xhr.status < 300) ||
xhr.status == 304 || xhr.status == 1223;
} catch (e) { }
return false;
};
//making sure the request is created
if (!xhr) {
return 404; // Not Found
}
//setting the function that is going to be called after the request is made
xhr.onreadystatechange = function() {
if (!httpSuccess(xhr)) {
return 503; //Service Unavailable
}
if (xhr.responseXML != null && xhr.responseText != null &&
xhr.responseXML != undefined && xhr.responseText != undefined) {
callback(xhr);
}
};
//open request call
xhr.open('GET', url, true);
//setup the headers
try {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Accept", "text/xml, application/xml, text/plain");
} catch ( ex ) {
window.alert('error' + ex.toString());
}
//send the request
try {
xhr.send('');
} catch (e) {
return 400; //bad request
}
return xhr;
};
这就是我调用函数来测试结果的方式:
window.onload = function() {
ajaxReq('ConferenceRoomSchedules.xml', function(xhr) {
//in firefox this line works fine,
//but in ie it doesnt not even showing an error
window.document.getElementById('schedule').innerHTML = xhr.responseText;
//firefox says ''xhr.responseXML is undefined'.
//and ie doesn't even show error or even alerts it.
window.alert(xhr.reponseXML.documentElement.nodeName);
});
}
这也是我第一次尝试使用 AJAX,所以可能有些东西我看不正确。 我一直在疯狂寻找任何关于为什么或如何解决它的迹象,但没有运气。 任何想法都会很棒。
编辑:
我知道有一个框架会更好,但是老板不想为一个 ajax 功能添加一个框架('just' 对于 ajax 来说不是一个公平的词:P)。所以我用纯javascript来做。
XML 文件格式正确,我可以在 Web 浏览器中很好地看到它,但为了完成,这是我正在使用的测试文件:
<?xml version="1.0" encoding="utf-8"?>
<rooms>
<room id="Blue_Room">
<administrator>somebody@department</administrator>
<schedule>
<event>
<requester>
<name>Johnny Bravo</name>
<email>jbravo@department</email>
</requester>
<date>2009/09/03</date>
<start_time>11:00:00 GMT-0600</start_time>
<end_time>12:00:00 GMT-0600</end_time>
</event>
</schedule>
</room>
<room id="Red_Room">
<administrator>somebody@department</administrator>
<schedule>
</schedule>
</room>
<room id="Yellow_Room">
<administrator>somebody@department</administrator>
<schedule>
</schedule>
</room>
</rooms>
编辑 2: 好消息是我说服了我的老板使用 jQuery,坏消息是 AJAX 仍然困扰着我。出于好奇,我会阅读更多有关它的信息。感谢您的提示,我将答案归功于 Heat Miser,因为他是最接近的工作提示。
【问题讨论】:
标签: javascript ajax cross-browser