Home > Web Front-end > JS Tutorial > body text

Ajax request global configuration that encapsulates jQuery_jquery

WBOY
Release: 2016-05-16 16:15:50
Original
1434 people have browsed it

Summary:

jQuery has become the most common js library in projects and the favorite library for front-end development. Below is the Ajax that encapsulates jQuery in the project, shared with everyone.

Code:

Copy code The code is as follows:

// ajax request parameters
var ajaxSettings = function(opt) {
var url = opt.url;
var href = location.href;
// Determine whether there is a cross-domain request
var requestType = 'jsonp';
If (url.indexOf(location.host) > -1)
        requestType = 'json';
requestType = opt.dataType || requestType;
// Whether to request asynchronously
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) {
               /*
*If dataType is json, how to determine whether the returned data is in json format? If not, convert it
* Common format of successful data
                 *                                             “code”: 200,
“data”: [],
                                                                                                                                                               *                                               * Data returned on failure
                 *                                             “code”: 200,
"info": 'error',
“success”: false // Failed                  *                                                               */
If((requestType === 'json' || requestType === "jsonp") && typeof(data) === "string") {
                  data = JSON.parse(data);
            }
                 if(data.success) {
                     opt.success(data);
            }

if(opt.error) {
                    opt.error(data);
            }

        },
        error: function(xhr, status, handler) {
            if (opt.error)
                opt.error();
        }
    };
};
function unescapeEntity(str) {
    var reg = /&(?:nbsp|#160|lt|#60|gt|62|amp|#38|quot|#34|cent|#162|pound|#163|yen|#165|euro|#8364|sect|#167|copy|#169|reg|#174|trade|#8482|times|#215|divide|#247);/g,
        entity = {
        ' '   : ' ',
        ' '   : ' ',
        '<'     : '<',
        '<'    : '<',
        '>'     : '>',
        '&62;'     : '>',
        '&'    : '&',
        '&'    : '&',
        '"'   : '"',
        '"'    : '"',
        '¢'   : '¢',
        '¢'   : '¢',
        '£'  : '£',
        '£'   : '£',
        '¥'    : '¥',
        '¥'   : '¥',
        '€'   : '?',
        '€'  : '?',
        '§'   : '§',
        '§'   : '§',
        '©'   : '©',
        '©'   : '©',
        '®'    : '®',
        '®'   : '®',
        '™'  : '™',
        '™'  : '™',
        '×'  : '×',
        '×'   : '×',
        '÷' : '÷',
        '÷'   : '÷'
    };
    if (str === null) {
        return '';
    }
    str = str.toString();
    return str.indexOf(';') < 0 ? str : str.replace(reg, function(chars) {
        return entity[chars];
    });
}
// 转换html的实体
$.ajaxSetup({
    global     : true,
    cache      : false,
    converters : {
        'text json' : function(response){
            return jQuery.parseJSON(unescapeEntity(response));
        }
    }
});
/*
*Ajax 请求权限异常
*   用户权限错误跳转登陆页
*   404错误跳转404页面
 */
$(document).ajaxComplete(function(evt, req, settings){
    if(req && req.responseJSON){
        var json = req.responseJSON;
        if(json.code === 403 && json.info === 'perm error' && !json.success){
            window.location.href = location.protocol '//' location.hostname;
            return;
        }
        if(json.code === 404 && !json.success) {
                 window.location.href = location.protocol '//' location.hostname '/404.html';
}
}
});
/*
*Ajax request error message
*Example: 500 error
*Return error message format
*{
* code: 500,
* info: System exception
*}
*/
$(document).ajaxError(function(evt, req, settings){
If(req && (req.status === 200||req.status === 0)){ return false; }
var msg = 'Error:';
If(req && req.responseJSON){
      var json = req.responseJSON;
          msg = json.code||'';
            msg = json.info||'System exception, please try again';
}else{
            msg = 'System exception, please try again';
}
alert(msg);
});

Summary:

When executing an Ajax request, you only need to call the ajaxSettings function, as follows:

Copy code The code is as follows:

$.ajax(ajaxSettings({
url: '',
Data: ''
}))

The above is the entire content of this article, I hope you all like it.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template