JQuery Ajax of method guidelines

  • 2020-03-30 04:21:48
  • OfStack

(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 quite powerful and has a lot of configurable parameters, the main points to note about this method are summarized.

1.             JQuery. Ajax () is requested asynchronously by default, using the parameter async to be false if synchronization is required. Because some applications must synchronize requests for data. For example, in some flash-js interactive applications, requesting a JS function requires that the data be returned immediately. At this point, you must make synchronous Ajax calls.

2.             If Ajax is a Get request, the returned data will be cached by the browser. If you do not want to be cached, you can set the cache parameter to false. Or the request can be sent with a timestamp, so the browser thinks it's a new request and reloads the data from the server. Of course, a request sent by a POST is not cached.

3.             DataType: the dataType that the server is expected to return. If not specified, jQuery will automatically return responseXML or responseText based on the HTTP package MIME information and pass it as a callback function parameter. The available values are:

(1) "XML ": returns an XML document, which can be processed by jQuery.

(2) "HTML ": returns plain HTML information; The included script tags are executed when the dom is inserted.

(3) "script": returns plain JavaScript code. The results are not automatically cached. Unless the "cache" parameter is set. Note: when a remote request is made (not under the same field), all POST requests become GET requests. (because it will be loaded using the script tags of the DOM)

(4) "json": returns json data.

(5) "jsonp": jsonp format. When calling a function in JSONP form, such as "myurl? The callback = & # 63;" JQuery will automatically replace ? Is the correct function name to execute the callback function.

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

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

4.             If the server returns a string or value, use a normal ajax call.

If the server returns a JSON object, it is best to use jquery.getjson or set dataType= JSON. Since it takes time for the browser to parse the JSON object, return the JSON object directly to save the parsing time, so as to avoid the error that the browser cannot get the returned data when the server has returned it.

5. Ajax calls take time, so you generally put all the processing code after the Ajax call into the callback method. This cannot be done:


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+='<tr>'+'<th>'+prizearray[obj[i].prizeno]+'</th>'
               str+='<td>'+'CD-KEY : '+obj[i].cdkey+'</td>'
               str+='<td>'+' Deadline: '+obj[i].expiratedate+' before '+'</td></tr>';
           }
           jQuery("#prizelist").append(str);
        }
}

Instead, you must put the processing code into the success function!


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<obj.length;i++ ){
                                    str+='<tr><th>'+prizearray[obj[i].prizeno]+'</th>';
                                    str+='<td>CD-KEY : '+obj[i].cdkey+'</td>';
                                    str+='<td> Deadline: '+obj[i].expiratedate+' before </td></tr>';
                                }
                                jQuery("#prizelist").append(str);                  
                               }
                   });
           }catch(e){}
        }
}

6. JQuery. GetJSON instance:


//Internal function to load and set the details of the debtor
    function innerShowDetail() {
       //Get data in JSON format
       $.getJSON('load.do',{id : userId}, function(json) {
           //Value
is set according to the key            for (key in json) {
              if(key == 'id'){
                  $('#detailDiv #' + key).val(json[key]);
              } else {
                  if(json[key] == ''){
                     //No value is set to null
                     $('#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 contents
           $('#detailDiv').removeAttr('class');
           dialog.setTitle(' Check the staff [' + json['userName'] + '] Detailed information on ');
           dialog.setContent($('#detailDiv').html());
       });
    }


Related articles: