简体   繁体   中英

Ajax message best practices

Say I need to use ajax to asynchronously ask the server for an xml file containing relevant data. What is the best practice on what this message should look like? Should it be a string like get_data or something similar? Should it be xml? I don't really need long polling since its a one-time (or close to it) request.

Thanks.

You can use standard a HTTP Post or Get to send the request to your server. If you don't need to specify any parameters to your server side script ( user_id, etc ) then simply appending get_data as a url parameter will work fine.

http://www.domain.com/script?get_data

If you need to send any parameters to the server in order to retrieve data it is best to encode the parameters in JSON or XML and send them as the data portion of your AJAX request. With JQuery and JSON data:

$.ajax({
    type: "GET",
    url: "http://www.domain.com/script",
    data: { key: "value", key2: "value2" },
    async: true,
    dataType: "json",
    success: function( data, textStatus ) { 
        someCallbackFucntion( data );
    }   
});

The message should be the url.

For example: http://www.example.com/get_data could return the data you need in the format you need (xml, json).

If you need some other data, use an other url. http://www.example.com/someotherdata

It really depends on the purpose, if everything else is XML, go for XML. Personally I perfer JSON (for the client-side at least).

In a recent implementation I made, I used a simple POST request where the key represented the type of data and the value contained the time-interval it should return.

Which could be (jQuery):

$.ajax({ 
    type: "POST", 
    url: "http://www.domain.com/script", 
    data: { stock_value: "last_30_min", group_activity: "last_20" }, 
    async: true, 
    dataType: "json", 
    success: function( data, textStatus ) {  
        someCallbackFucntion( data ); 
    }    
});

A server-side controller would then handle the request appropriately and the client-side would know what data to expect when it returned. Also the key and value would be humanly readable from both client- and server-side. Of course the time-intervals could be a timestamp or otherwise, whatever fits the need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM