开发者

Javascript to jQuery Conversion for an xml ajax call

I have the following script

if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("GET", "/getSelectedProductData?offerCollectionRef=" + offerCollectionRef + "&brandRef=" + brandRef + "&priceRef=" + priceRef + "&defaultSmallImage=" + defaultSmallImage + "&offerCode=" + offerCode + "&index=" + index, false);    

xmlhttp.send();
x开发者_如何学GomlDoc = xmlhttp.responseXML;

I know how to write a $.ajax in jQuery. But I am stuck at how to send data.

My questions are

  1. The return is XML and so the dataType: xml. am I correct?
  2. How should I pass the data to the url?

Please elaborate on these things.

Disclaimer: The thing is that I couldn't test it myself and so this question.


1 The return is XML and so the dataType: xml. am I correct?

You actually don;t need to specify it if the server sets proper Content-Type header to text/xml. jQuery will automatically consider the result as XML

2 How should I pass the data to the url?

You could use the data hash:

$.ajax({
    url: '/getSelectedProductData',
    type: 'GET',
    dataType: 'xml', // not necessary if the server sets the Content-Type: text/xml response header
    data: { 
        offerCollectionRef: offerCollectionRef,  
        brandRef: brandRef,
        priceRef: priceRef,
        defaultSmallImage: defaultSmallImage,
        offerCode: offerCode,
        index: index
    },
    success: function(xml) {
        // ...
    }
});

Also you seem to be sending a synchronous request by setting the async parameter to false. To emulate the same with jQuery you could add the async: false option. This being said, you probably shouldn't be doing it. SJAX (sync javascript) will block the browser during the request and ruin the user experience.


  1. Yep.
  2. You can use the data property when passing settings to $.ajax(). It can be an object (it will be converted to a query string) or a query string. Please check the jQuery Manual for further details.

Excerpt from the manual:

data (Object, String) Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

So from your example, url shall be '/getSelectedProductData', and data could be everything after ?. Or you can organize them into an object like { 'offerCollectionRef': offerCollectionRef, ... }, it is a bit more readable.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜