开发者

Error callback every time when trying to POST XML using jQuery in non-IE browsers

I am trying to communicate with Google's spell check service using jQuery. Google's service requires that you post XML and it will in turn return an XML response. In IE, the success callback gets hit every time, but in non-IE browsers (tested in Firefox and Chrome) the error callback is getting hit ev开发者_开发百科ery time.

The biggest difference is in how the XML that is posted is created. For IE, an ActiveX object is getting created; for all other browsers the DOMParser is used (example from w3schools).

Below is my test code (NOTE: 'spell-check' represents the ID of an HTML button.) What am I missing or need to change to successfully post XML from jQuery across browsers?

<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;
            }
        });
    });
});


The dom Parser chokes on the <?xml version="1.0"?> part.. Remove it and it should work fine ..

[edit]

Now that we fixed the parser failing, lets look at the ajax call..

You need to convert the xml object to a string before sending it through a POST.. This means that you should send directly the xmlstring without parsing it first (if there is nothing else you need to do with the xml).. remember to escape it first..

change data: createXMLDocument(xmlString), to data: escape(xmlString), and try once more ..

[edit 2]

Just noticed... you cannot make ajax calls crossdomain (it is not safe) unless they are JSONP .. you can only talk with your own domain .. the workaround is to make a server-side page (asp/php etc..) that will make the crossdomain call and return the results to your own javascript call..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜