jquery的Ajax和fetch的demo

大家好,我是烤鸭:

简单说一下最ajax的两种方式fetch和jquery ajax,主要是常用的参数和demo。

(一)ajax

jquery下载地址

https://jquery.com/download/

$.ajax( {    
    url:'url',// 跳转到 action    
    data:{    
             'data' : 'data'    
    },    
    type:'post',    
    cache:false,    
    dataType:'json',    
    //同步,默认为true
    //async: false, 
    //跨域
    //dataType:'jsonp',   
    //jsonp : 'callback',
    success:function(data) {    
        console.log(data);
        if(data.msg =="true" ){    
            alert("修改成功!");    
        }else{    
            console.log(data.msg);    
        }    
     },    
     error : function() {    
          alert("异常!");    
     }    
});  

是否同步:

常用的设置都在上边了,是是否同步async:默认true,就是异步请求。如果有什么操作是需要等到ajax返回再执行的话,请改成false。

跨域请求:

dataType:'jsonp'和jsonp:'callback',这个callback是自定义的,需要请求完成后服务器端返回一个json的格式是callback(data),data是你想返回的内容。随便叫什么jsonpCallback,返回就是jsonpCallback(data)。

(二) fetch

fetch下载的地址:

https://github.com/github/fetch

这是一个简单的fetch请求

// 链式处理,将异步变为类似单线程的写法: 高级用法.
fetch('/some/url').then(function(response) {
    return response.json();//... 执行成功, 第1步...
}).then(function(json) {
    console.log(json);
    // ... 执行成功, 第2步...
}).catch(function(err) {
    // 中途任何地方出错...在此处理 :( 
}):
从 fetch()返回的 Promise 将不会拒绝HTTP错误状态, 即使响应是一个 HTTP 404 或 500。相反,它会正常解决 (其中ok状态设置为false), 并且仅在网络故障时或任何阻止请求完成时,它才会拒绝。所以这类返回值需要我们处理。
    可以改进上边的代码,加两个方法
    
function checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
        return response
    } else {
        var error = new Error(response.statusText)
        error.response = response
        throw error
    }
}
function parseJSON(response) {
    return response.json()
}
    修改后(demo):

    

var form= document.querySelector('form'); //form表单
var data = new FormData(form);
data.append("data","data");
fetch(url, {
        method: 'POST',
        credentials: 'include',  //带cookie
        mode: "cors",//same-origin(同源请求)、no-cors(默认)和cros(允许跨域请求)
        body: data
    }).then(checkStatus)
.then(parseJSON).then(function(json) {
    console.log(json);
    // ... 执行成功, 第2步...
}).catch(function(err) {
    // 中途任何地方出错...在此处理 :( 
});

   下面介绍几个常用的参数:


    method:请求方式,GET, POST, PUT, DELETE, HEAD
    credentials: 默认不带cookie,如果想带的话,就传'include'

    mode:same-origin(同源请求)、no-cors(默认)和cros(允许跨域请求)
    body: 参数,通常是页面上表单。

    这里的data,就已经是form表单内的数据了,加上后边添加的"data"。

    

    更多有关fetch请求的,请看这个大神的这篇文章。

    http://blog.csdn.net/renfufei/article/details/51494396

    



猜你喜欢

转载自blog.csdn.net/angry_mills/article/details/79049250