ajax请求方法

ajax请求:

1、这里介绍下原生方法:

get方法:
    function getMethod(){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readystate == 4){
                if((xhr.status >=200)&&(xhr.status < 300) || xhr.status == 304){
                    console.log(responseText);
                } else {
                    console.log('request was unsuccessful: '+ xhr.status);
                }
            }
        };
        xhr.open('get','test.php',false);
        xhr.send(null);
    }

post方法:
    function postMethod(){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readystate == 4){
                if((xhr.status == 200)&&(xhr.status < 300)||(xhr.status == 304)){
                    console.log(responseText);
                } else {
                    console.log('request was unsuccessful: '+ xhr.status);
                }
            }
        };
        xhr.open('post','test.php',true);
        xhr.send([text]); // text可有可无
    }
    

open('method',url,boolean);
  method方法常见为两种:get 和 post,两者区别这里不再讲述;
  url:请求的路径
  boolean:布尔值,false为同步请求,此时js代码会等待服务器响应之后再继续执行;true为异步请求,js继续执行而不必等待响应;

xhr对象的readystate属性,检测当前活动阶段,readystate有4个取值:
  0:未初始化,尚未调用open方法;
  1:启动,已调用open方法,但尚未调用send方法;
  2:发送,已调用send方法,但尚未接收到响应;
  3:接收,已经接收到部分响应数据;
  4:完成,已经接收到全部响应数据,且可以在客户端使用了;


xhr的其它常用属性:
  responseText: 作为响应主体被返回的文本;
  status:响应的http状态
  statusText: Http状态的说明
  responseXML:若响应的内容类型是‘text/xml’或‘application/xml’,这个属性中将保存包含着响应数据的xml dom文档;

2、jquery中方法

   第一种写法: $.ajax({
                    type: 'post',
                    dataType: 'json',
                    url: '',
                    data: {
                    },
                    success: function(){},
                    error: function(){}
               });
第二种写法:$.ajax({ type:
'post', dataType: 'json', url: '', data: {}, async: false }).done(function(resp){ console.log(resp); // 相当于第一种的success }).fail(function(){ //相当于第一种的error });
第三种写法: $.ajax({ type:
'post', dataType: 'json', data: {}, url: '', async: false // 默认是true,异步 }).then(function(resolve,reject){ // then 方法组合了done和fail方法; });

以上后两种jQuery的ajax方法,对jQuery版本有要求,具体可参考jQuery官网

原文地址:https://www.cnblogs.com/wuting/p/9145845.html