Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The instructions for using the json data called ajax in jquery


May 08, 2021 JSON


Table of contents


$.get() and $.post ()

$.get() and $.post () are basically the same methods, so here's an example of $.post() to explain!
  • Scenario 1: $.post ("url", function); T he data returned at this time is not processed, so it is not in the johnson format!
  • Scenario 2: $.post ("url", function, "json"); A t this point, although the returned data is specified as jason format, it is not!
  • Scenario 3: $.post ("url", "," function); T he incoming parameters are empty at this point and the returned data format is not specified, so it is not the johnson format!
  • Scenario 4: $.post ("url", s, function, "json"); T he data in the jason format is returned correctly!
Important: When you want to treat the returned data as a jason format, you must pass in the parameters (the parameters are empty and write as " ) and you must also specify the return type as "json"!
$.ajax({
url:"url",
dataType:"json",
type:"get"
success:function
})
Important: To specify dataType as "json", you'll get jason format data in both get and post, but I suggest that in order to be consistent with the two methods above, it's best to add data: .
$.getJSON("url",function)

Key points: get the jason format data in the way of get, is $.get () convenient to write it!

jQuery Ajax usage is detailed

jQuery Ajax is very common in web application development, it mainly includes ajax, get, post, load, getscript and so on, these commonly used no-refresh operation methods, when dealing with complex ajax requests, jQuery uses jQuery.ajax() method to handle.

There are some simple methods in jQuery that encapsulate the jQuery.ajax() method so that we don't need to use the jQuery.ajax() method when dealing with some simple Ajax events.

The following 5 methods perform a short form of a general Ajax request and should use jQuery.ajax() when handling complex Ajax requests.

1.load(url,[data],[callback])

Load the remote HTML file code and insert it into the DOM, which is automatically converted to POST by passing parameters using getT by default.

  • url: The remote url address to load
  • data: Key/value data sent to the server
  • Callback: A callback function when loaded successfully
The sample code is as follows:

//无参数、无回调函数
$("#showload").load("load.htm");
//无回调函数
$("#showload").load("load.htm", { "para": "para-value" });
$("#showload").load("load.htm", { "para": "para-value" },
    function() {
        //处理
    })

The contents of the loaded file will be displayed here

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

Use get data from the server side using get.

  • The URL address at which the request was sent
  • The data to send to the server
  • The callback function on successful load

The sample code is as follows:

$.get("jqueryget.htm", { "id": this.id },
    function(req) {
        //成功时的回调方法
        $("#showget").html(req);
    });
})

Using the $.get() method, you get different logos by passing the id. It's worth noting that the request is obtained through the get method at this point, so use Request.QueryString when getting parameter values, and you can see the difference between Request Request.QueryString

3. Baidu logo Google logo

Here will logo3.jQuery.post (url, s data), callback)
Use POST to make asynchronous requests. The difference with jQuery.get() is the way it is requested, so it's not specifically explained here that the usage method is similar to jQuery.get().

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

Request a JavaScript file to be loaded and executed via GET. This technique, which has been mentioned in previous articles, is also a simple way to use jQuery.ajax, and you can look at ajax loading js, so it's not particularly explained here.

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

Get the data in the json format by get it.

The sample code is as follows:

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(req) {
    $.each(req.items, function(i, item) {
        if (i == vnum) {
            $("<img src="" + item.media.m + "" title="" + item.title + "" />").appendTo("#showjson");
        }
    });
});

Again, this is a short-form approach to the jQuery.ajax() approach, similar to the following:

List of parameters:

The name of the argument Type Describe
Url String (Default: Current page address) to send the requested address.
type String (Default: "GET") request method ("POST" or "GET"), default to "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but only some browsers support it.
timeout Number Set the request time-out time in milliseconds. This setting overrides the global settings.
async Boolean (default: true) By default, all requests are asynchronous. I f you need to send a sync request, set this option to false. Note that the sync request locks the browser and the user must wait for the request to complete before executing.
beforeSend Function You can modify the functions of the XMLHttpRequest object before sending a request, such as adding a custom HTTP header. The XMLHttpRequest object is the only parameter.
function (XMLHttpRequest) {  this; // the options for this ajax request}
cache Boolean (default: true) jQuery 1.2 New feature, set to false, will not load request information from the browser cache.
complete Function The callback function (called when the request succeeds or fails) after the request is completed. Argument: XMLHttpRequest object, success information string.
function (XMLHttpRequest, textStatus) {  this; // the options for this ajax request}
contentType String (Default: "application/x-www-form-urlencoded") the type of content encoding when sending information to the server. The default values are appropriate for most applications.
data Object,
String
The data sent to the server. W ill be automatically converted to the request string format. T he GET request is attached to the URL. R eview the processData option description to prevent this automatic conversion. M ust be in Key/Value format. I f it is an array, jQuery will automatically correspond to the same name for different values. Such as the "foo: " bar1", "bar2" , " ,
dataType String

The type of data expected to be returned by the server. If not specified, jQuery will automatically return responseXML or responseText based on http package MIME information and pass the available values as callback function parameters:

"xml": Returns the XML document, which can be processed by jQuery.

"html": Returns plain text HTML information;

"script": Returns plain text JavaScript code. Results are not automatically cached.

"json": Returns JSON data.

"jsonp": JSONP format. W hen a function is called in JSONP form, such as "myurl?callback=?" jQuery will be replaced automatically? Is the correct function name to execute the callback function.

error Function (default: This method is called when the automatic judgment (xml or html)) request fails. This method has three parameters: the XMLHttpRequest object, the error message, and (possibly) the wrong object captured.
function (XMLHttpRequest, textStatus, errorThrown) {  // 通常情况下textStatus和errorThown只有其中一个有值   this; // the options for this ajax request}
global Boolean (default: true) whether to trigger a global AJAX event. S etting to false will not trigger a global AJAX event, such as ajaxStart or ajaxStop. Can be used to control different Ajax events
ifModified Boolean (default: false) get new data only when the server data changes. Use the HTTP package Last-Modified header information to determine.
processData Boolean (default: true) By default, the data sent is converted to an object (not technically a string) to match the default content type "application/x-www-form-urlencoded". If you want to send DOM tree information or other information that you do not want to convert, set it to false.
success Function The callback function after the request was successful. This method has two parameters: the server returns the data and returns the state
function (data, textStatus) {  // data could be xmlDoc, jsonObj, html, text, etc...  this; // the options for this ajax request}

Here are a few Ajax event parameters: beforeSend, success, complete, error. /b12>We can define these events to handle each of our Ajax requests well. Note that the this in these Ajax events is a picture of the thiss that points to the option information requested by Ajax (see the this picture when you say get() method).

The code is as follows:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

Maybe you haven't used jason data yet, my small station has mentioned the use of jason several times, if you are not familiar with the json format, you can look at the value of jquery mobile listbox, jQuery under the use of json examples

Get jason data

Here will randomly display a json data so far we have summarized the jQuery.ajax five short-form methods, let's focus on the jQuery.ajax() method, in use, the author is also often used jQuery.ajax(), because in most cases, we need to axaj request error situation to capture and deal with.

6.jQuery.ajax()

Use the jQuery.ajax() method to get the data, give a common write below, and make a corresponding comment.

The code is as follows:

$.ajax({
    url: "http://www.hzhuti.com",    //请求的url地址
    dataType: "json",   //返回格式为json
    async: true, //请求是否异步,默认为异步,这也是ajax重要特性
    data: { "id": "value" },    //参数值
    type: "GET",   //请求方式
    beforeSend: function() {
        //请求前的处理
    },
    success: function(req) {
        //请求成功时处理
    },
    complete: function() {
        //请求完成的处理
    },
    error: function() {
        //请求出错处理
    }
});

Use jQuery.ajax()
The data is displayed here.


$.ajax practical application example:

//1.$.ajax带json数据的异步请求
var aj = $.ajax( {  
    url:'productManager_reverseUpdate',// 跳转到 action  
    data:{  
             selRollBack : selRollBack,  
             selOperatorsCode : selOperatorsCode,  
             PROVINCECODE : PROVINCECODE,  
             pass2 : pass2  
    },  
    type:'post',  
    cache:false,  
    dataType:'json',  
    success:function(data) {  
        if(data.msg =="true" ){  
            // view("修改成功!");  
            alert("修改成功!");  
            window.location.reload();  
        }else{  
            view(data.msg);  
        }  
     },  
     error : function() {  
          // view("异常!");  
          alert("异常!");  
     }  
});

//2.$.ajax序列化表格内容为字符串的异步请求
function noTips(){  
    var formParam = $("#form1").serialize();//序列化表格内容为字符串  
    $.ajax({  
        type:'post',      
        url:'Notice_noTipsNotice',  
        data:formParam,  
        cache:false,  
        dataType:'json',  
        success:function(data){  
        }  
    });  
} 

//3.$.ajax拼接url的异步请求
var yz=$.ajax({  
     type:'post',  
     url:'validatePwd2_checkPwd2?password2='+password2,  
     data:{},  
     cache:false,  
     dataType:'json',  
     success:function(data){  
          if( data.msg =="false" ) //服务器返回false,就将validatePassword2的值改为pwd2Error,这是异步,需要考虑返回时间  
          {  
               textPassword2.html("<font color='red'>业务密码不正确!</font>");  
               $("#validatePassword2").val("pwd2Error");  
               checkPassword2 = false;  
               return;  
           }  
      },  
      error:function(){}  
});

//4.$.ajax拼接data的异步请求
$.ajax({   
    url:'<%=request.getContextPath()%>/kc/kc_checkMerNameUnique.action',   
    type:'post',   
    data:'merName='+values,   
    async : false, //默认为true 异步   
    error:function(){   
       alert('error');   
    },   
    success:function(data){   
       $("#"+divs).html(data);   
    }
});