Home > Web Front-end > JS Tutorial > jQuery Ajax() method usage guide_jquery

jQuery Ajax() method usage guide_jquery

WBOY
Release: 2016-05-16 16:30:54
Original
1530 people have browsed it

jQuery provides simple and powerful selector functions, and also provides good support for Ajax operations. In terms of Ajax, in addition to providing the underlying jQuery.ajax() method, jQuery also provides the following simple methods:

(1) jQuery.get(url, [data], [callback], [type])

(2) jQuery.getJSON(url, [data], [callback])

(3) jQuery.getScript(url, [callback])

(4) jQuery.post(url, [data], [callback], [type])

Since jQuery.ajax() is relatively powerful and has many configurable parameters, we will now mainly summarize the precautions for this method.

1. jQuery.ajax() is requested asynchronously by default. If synchronization is required, use the parameter async to false. Because some applications must request data synchronously. For example, in some Flash and JS interactive applications, requesting a JS function requires immediate return data. At this time, synchronous Ajax calling must be used.

2. If Ajax is a Get request, the returned data will generally be cached by the browser. If you do not want to be cached, you can set the cache parameter to false; or send the request with a timestamp, so that the browser will think it is new. request while reloading the data from the server. Of course, if the request is sent by POST, it will not be cached.

3. DataType: The data type expected to be returned by the server. If not specified, jQuery will automatically return responseXML or responseText based on the HTTP packet MIME information and pass it as a callback function parameter. Available values:

(1) "xml": Returns an XML document that can be processed with jQuery.

(2) "html": Returns plain text HTML information; the included script tag will be executed when inserted into the dom.

(3) "script": Returns plain text JavaScript code. Results are not cached automatically. Unless the "cache" parameter is set. '''Note:''''When making remote requests (not under the same domain), all POST requests will be converted into GET requests. (Because the DOM script tag will be used to load)

(4) "json": Return JSON data.

(5) "jsonp": JSONP format. When calling a function using JSONP format, such as "myurl?callback=?" jQuery will automatically replace ? with the correct function name to execute the callback function.

(6) "text": Returns a plain text string

Among them, "script" and "json" settings can solve the cross-domain problem of Ajax.

4. If the server returns a string or numerical value, just use ordinary ajax call.

If the server returns a JSON object, it is best to use jQuery.getJSON or set dataType=json. Because it takes time for the browser to parse the JSON object, directly returning the JSON object saves parsing time and avoids errors in which the server clearly returns data but the browser cannot get it.

5. Ajax calls take time, so generally all processing codes after Ajax calls are placed in the callback method. This approach cannot be used:

Copy code The code is as follows:

function getMyPrizeList(){
    if(isNotEmpty(uid)){
        var obj=new Object();
        try{
          jQuery.ajax({type:"GET",url:"someurl",async:false,cache:false,dataType:"script",scriptCharset:"gbk",success:function(json){
                     obj=json;
                  }
              });
           }catch(e){}
           obj=eval("(" obj ")");
           //alert(obj);
           var str="";
           for(var i in obj)
           {
               str ='' '' prizearray[obj[i].prizeno] ''
               str ='' 'CD-KEY:' obj[i].cdkey ''
               str ='' '期限:' obj[i].expiratedate '前' '';
           }
           jQuery("#prizelist").append(str);
        }
}

而必须这样处理:即将处理代码放到success函数里面!

复制代码 代码如下:

function getMyPrizeList(){
    if(isNotEmpty(uid)){
        var obj=new Array();
        try{
                  jQuery.ajax({type:"GET",url:"someurl",
                               cache:false,
                               dataType:"script",
                               scriptCharset:"gbk",
                               success:function(json){
                                 try{
                                      obj=result; 
                                }catch(e){}
                                jQuery("#prizelist").html("");
                                var str="";
                                for(var i=0;i                                     str ='' prizearray[obj[i].prizeno] '';
                                    str ='CD-KEY:' obj[i].cdkey '';
                                    str ='期限:' obj[i].expiratedate '前';
                                }
                                jQuery("#prizelist").append(str);                  
                               }
                   });
           }catch(e){}
        }
}

6. jQuery.getJSON实例:

复制代码 代码如下:

//Internal function to load debtor details and set values
Function innerShowDetail() {
// Get data in JSON format
         $.getJSON('load.do',{id : userId}, function(json) {
// Set value
based on key for (key in json) {
If(key == 'id'){
                           $('#detailDiv #' key).val(json[key]);
                  } else {
If(json[key] == ''){
// No value set to empty
                                $('#detailDiv #' key).html(' ');
                              } else if(key == 'sex'){
                         $('#detailDiv #' key).html(json[key] == '0' ? 'Female' : 'Male');
                            } else if(key == 'group'){
If(json[key] != null) {
$('#detailDiv #' key).html(json[key]['groupName']);
                    }
                     } else {
                                $('#detailDiv #' key).html(json[key]);
                 }
              }
           }
//Set the dialog title and content
               $('#detailDiv').removeAttr('class');
Dialog.setTitle('View person[' json['userName'] '] details');
Dialog.setContent($('#detailDiv').html());
});
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template