The use of Jquery Ajax

Ajax overview

Ajax is to load remote data through HTTP request. It is usually used to customize some http requests to flexibly complete the data interaction requirements between the front end and the back end.

Note that all options can be set globally via the $.ajaxSetup() function.

The reason why JQuery Ajax can send http requests is to call the XMLHttpRequest object (native ajax) in html.

There is also a cross-domain Ajax. This will be introduced at the end.

General format of Ajax

$.ajax({
     type: 'POST',
     url: url ,
    date: date,
    success: success ,
    dataType: dataType
});

Ajax parameter description

parameter name Types of describe
url String (default: current page address) The address to send the request to.
type String (Default: "GET") Request method ("POST" or "GET"), default is "GET". Note: Other HTTP request methods such as PUT and DELETE can also be used, but are only supported by some browsers.
timeout Number Set the request timeout in milliseconds. This setting will override the global setting.
async Boolean (Default: true) By default, all requests are asynchronous. Set this option to false if you need to send synchronous requests. Note that synchronous requests will lock the browser, and other user operations must wait for the request to complete before they can be performed.
beforeSend Function Functions that modify the XMLHttpRequest object before sending the request, such as adding custom HTTP headers. The XMLHttpRequest object is the only parameter.
function (XMLHttpRequest) {  this; // the options for this ajax request}
cache Boolean (default: true) New in jQuery 1.2, set to false will not load request information from browser cache.
complete Function The callback function after the request is completed (called when the request succeeds or fails). Parameters: XMLHttpRequest object, success message string.
function (XMLHttpRequest, textStatus) {  this; // the options for this ajax request}
contentType String (default: "application/x-www-form-urlencoded") The content encoding type when sending information to the server. The default value is suitable for most applications.
data Object,
String
Data sent to the server. will be automatically converted to request string format. It will be appended to the URL in GET requests. See the processData option description to disable this automatic conversion. Must be in Key/Value format. If it is an array, jQuery will automatically assign different values ​​to the same name. For example {foo:["bar1", "bar2"]} is converted to '&foo=bar1&foo=bar2'.
dataType String

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

"xml": Returns an XML document, which can be processed with jQuery.

"html": Returns plain text HTML information; contains script elements.

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

"json": Returns JSON data.

"jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。

 

 

 

 

 

error Function (默认: 自动判断 (xml 或 html)) 请求失败时将调用此方法。这个方法有三个参数:XMLHttpRequest 对象,错误信息,(可能)捕获的错误对象。
function (XMLHttpRequest, textStatus, errorThrown) {  // 通常情况下textStatus和errorThown只有其中一个有值   this; // the options for this ajax request}
global Boolean (默认: true) 是否触发全局 AJAX 事件。设置为 false 将不会触发全局 AJAX 事件,如 ajaxStart 或 ajaxStop 。可用于控制不同的Ajax事件
ifModified Boolean (默认: false) 仅在服务器数据改变时获取新数据。使用 HTTP 包 Last-Modified 头信息判断。
processData Boolean (默认: true) 默认情况下,发送的数据将被转换为对象(技术上讲并非字符串) 以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。
success Function 请求成功后回调函数。这个方法有两个参数:服务器返回数据,返回状态
function (data, textStatus) {  // data could be xmlDoc, jsonObj, html, text, etc...  this; // the options for this ajax request}

Ajax的一些例子

//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);  
    }
});

Ajax需要注意的一些地方

  1.data主要方式有三种,html拼接的,json数组,form表单经serialize()序列化的;通过dataType指定,不指定智能判断。

  2.$.ajax只提交form以文本方式,如果异步提交包含<file>上传是传过不过去,需要使用jquery.form.js的$.ajaxSubmit

 

Ajax跨域请求

  默认情况下,ajax只能给自己的域名发送ajax请求。

  跨域请求是指通过ajax去访问非本网站域名,与其他网站进行数据交互。这种请求受到浏览器“同源策略”的限制,会被浏览器本身拦截(在收到回应数据的时候被浏览器拦截,实际请求已经发送出去)。

解决跨域的两种方式

  jsonp 和 跨域资源共享就是解决ajax跨域请求的两种方式。具体案例,可以查看链接:Ajax大保健全套




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324814378&siteId=291194637