AJAX

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

Ajax通信流程

  • 首先创建一个ajax对象
    初始时:

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

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

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

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

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

setRequestHeader

send

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

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

同源策略

跨域资源访问

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

CORS

Frame代理

JSONP

//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( '&' );
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容