首页 > 语言 > JavaScript > 正文

封装了jQuery的Ajax请求全局配置

2024-05-06 14:46:17
字体:
来源:转载
供稿:网友

摘要:

  jQuery已经成为项目中最常见的js库,也是前端开发最喜欢使用的库。下面是在项目中封装了jQuery的Ajax,分享给大家。

代码:

代码如下:
// ajax 请求参数
var ajaxSettings = function(opt) {
    var url = opt.url;
    var href = location.href;
    // 判断是否跨域请求
    var requestType = 'jsonp';
    if (url.indexOf(location.host) > -1)
        requestType = 'json';
    requestType = opt.dataType || requestType;
    // 是否异步请求
    var async = (opt.async === undefined ? true : opt.async);
    return {
        url: url,
        async: async,
        type: opt.type || 'get',
        dataType: requestType,
        cache: false,
        data: opt.data,
        success: function(data, textStatus, xhr) {
            /*
            *如果dataType是json,怎判断返回数据是否为json格式,如果不是进行转换
            * 成功数据通用格式
            *   {
            *       "code": 200,
            *       "data": [],
            *       "success": true // 成功
            *   }
            *   失败返回的数据
            *   {
            *       "code": 200,
            *       "info": 'error',
            *       "success": false // 失败
            *   }
             */
            if((requestType === 'json' || requestType === "jsonp") && typeof(data) === "string") {

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选