我正在尝试使用jQuery与谷歌的拼写检查服务进行通信。Google的服务要求您发布XML,然后它将返回一个XML响应。在IE中,每次都会触发成功回调,但在非IE浏览器中(在Firefox和Chrome中测试),每次都会触发错误回调。
最大的区别在于如何创建发布的XML。对于IE,将创建一个ActiveX对象;对于所有其他浏览器,将使用DOMParser (来自w3schools的示例)。
下面是我的测试代码(注意:‘拼写检查’代表一个HTML按钮的ID。)为了从jQuery跨浏览器成功发布XML,我缺少或需要更改哪些内容?
<script type="text/javascript">
var xmlString = '<?xml version="1.0"?><spellrequest><text>mispell</text></spellrequest>';
function createXMLDocument(s) {
var xmlDoc;
if (window.DOMParser) {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(s, 'text/xml');
} else {
xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
xmlDoc.loadXML(s);
}
return xmlDoc;
}
$(function() {
$('#spell-check').live('click', function(e) {
e.preventDefault();
$.ajax({
cache: false,
contentType: 'text/xml',
data: createXMLDocument(xmlString),
dataType: 'xml',
processData: false,
type: 'POST',
url: 'https://www.google.com/tbproxy/spell?lang=en',
success: function(data, textStatus, XMLHttpRequest) {
alert(textStatus);
//debugger;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
//debugger;
}
});
});
});
发布于 2010-03-01 23:08:53
dom解析器在<?xml version="1.0"?>部分阻塞..去掉它,它应该可以正常工作..
编辑
现在我们修复了解析器失败的问题,让我们看一下ajax调用..
在通过POST发送xml对象之前,需要将其转换为字符串。这意味着您应该直接发送xmlstring,而不必先对其进行解析(如果不需要对xml做任何其他操作)..记得要先避开它..
将data: createXMLDocument(xmlString),更改为data: escape(xmlString),,然后重试。
编辑2个
刚刚注意到..。您不能进行跨域(it is not safe)的ajax调用,除非它们是JSONP。您只能与您自己的域对话。the workaround是做一个服务器端的页面(asp/php等)。这将进行跨域调用,并将结果返回给您自己的javascript调用。
https://stackoverflow.com/questions/2356644
复制相似问题