AJAX

Asynchronous JavaScript and XML
用js去异步的获取XML作为数据交换的格式

Ajax通信流程

  • 首先创建一个ajax对象
    初始时:
AJAX_第1张图片

调用open()方法:开启一个请求但没有向服务端发起请求

AJAX_第2张图片

调用send()方法:正式的向服务器端发起请求

AJAX_第3张图片

当服务器端开始返回请求数据的时候,浏览器端接收到这个数据

AJAX_第4张图片

浏览器端结束请求的时候:

AJAX_第5张图片

Ajax调用示例

//创建XHR对象
var xhr = new XMLHttpRequest();
//处理返回数据
xhr.onreadystatechange = function (callback){
    if(xhr.readyState == 4){
        if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
            callback(xhr.responseText);
        }else{
           alert('Request was unsuccessful: ' + xhr.status);
        }
    }
}
//发送请求
xhr.open('get','example.json',true);
xhr.setRequestHeader('myHeader','myValue');
xhr.send(null);

open

AJAX_第6张图片

setRequestHeader

AJAX_第7张图片

send

AJAX_第8张图片

向服务器端发送一个带查询参数的请求,请求参数序列化

AJAX_第9张图片
function serialize(data){
    if(!data){return ''};
    var pairs = [];
    for(var name in data) {
        if(!data.hasOwnProperty(name)){continue;}
        if(typeof data[name] === 'function'){continue;}
        var value = data[name].toString();
        name = encodeURIComponent(name);
        value = encodeURIComponent(value);
        pairs.push(name + '=' + value);
    }
    return pairs.join('&');
}

GET请求

var url = 'example.json?' + serialize(formdata);
xhr.open('get',url,true);
xhr.send(null);

POST请求

xhr.open('post','example.json',true);
xhr.send(serialize(formdata));

同源策略

AJAX_第10张图片

跨域资源访问

  • 不满足同源策略的资源访问,叫跨域资源访问
  • w3c定义了CORS
  • 现代浏览器已经实现对CORS的支持

CORS

AJAX_第11张图片

Frame代理

AJAX_第12张图片

JSONP

AJAX_第13张图片
//url    {String}    请求资源的url
//options    {Object}    请求的查询参数
//callback    {Function}    请求的回调函数,接收XMLHttpRequest对象的responseText属性作为参数
function get(url, options, callback){
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(callback){
        if(xhr.readyState == 4){
            if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
                callback(xhr.responseText);
            }else{
                alert('Request was unsuccessful: ' + xhr.status);
            }
        }
    }  
    xhr.open('get', url+'?'+serialize(options), true);
    xhr.send(null);
}
        
       
function serialize(data){
    if(!data) return '';
    var pairs = [];
    for(var name in data){
        if(!data.hasOwnProperty(name)) continue;
        if(typeof data[name] === 'function') continue;
        var value = data[name].toString();
        name = encodeURIComponent(name);
        value = encodeURIComponent(value);
        pairs.push(name + '=' + value);
    }
    return pairs.join('&');
}
function post( url, options, callback ){
    var xhr = null;
    if( window.XMLHttpRequest ){
        xhr = new XMLHttpRequest();
    }else{
        //IE6以下
        xhr = new ActiveXObject( 'Microsoft.XMLHTTP' );
    }
    xhr.open( 'post', url, true );
    xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
    xhr.send( serialize(options) );
    xhr.onreadystatechange = function () {
        if( xhr.readyState == 4 ){
            if( (xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 ){
                callback( xhr.responseText );
            }else{
                alert( 'Request was unsuccessful' + xhr.status );
            }
        }
    };
}
      
function serialize( data ){
    if( !data ) return '';
    var pairs = [];
    for( var name in data ){
        if( !data.hasOwnProperty(name) ) continue;
        if( typeof data[name] === 'function' ) continue;
        var value = data[name];
        name = encodeURIComponent( name );
        value = encodeURIComponent( value );
        pairs.push( name + '=' + value );
    }
    return pairs.join( '&' );
}

你可能感兴趣的:(AJAX)