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

How to use ajax encapsulated function jsonp

一个新手
Release: 2017-09-09 15:08:04
Original
1530 people have browsed it

// 封装ajax jsonp处理
var api_url = '';
function ajax(url, para, success, error) {
    $.ajax({
        type: para.type ? para.type: 'GET',
        url: url,
        contentType: 'application/json',
        // 
        dataType: para.dataType || 'jsonp',
        // 数据格式
        async: para.async,
        // 同步异步
        data: para.data,
        // 请求字段名
        beforeSend: function(xhr) {
            // 发送数据前
        },
        success: function(res) {
            if (success) success(res);
        },
        error: function(request) {
            var res = request.responseText;
            if (typeof(res) == 'string') {
                res = JSON.parse(request.responseText); // JSON 处理返回的错误 解析
            }
            if (error) {
                error(res); // 返回的错误打印出来
            }
            if (res.code == 206 || res.code == 207) {
                // 服务器错误代码处理
            }
        }
    });
}
function ajax_general(option, para, success, error) {

    if (option.async == undefined) {
        option.async = true; // 判断同步与异步 
    }

    option.type = option.type ? option.type: 'POST'; // 判断get或post方式。如果没有设置。默认post 
    var url = api_url + option.action; // 定义 url 请求地址
    option.data = para; // 请求的字段
    ajax(url, option,
    function(res) {
        success(res);
    },
    error);
}
Copy after login

Calling method:

ajax_general({
    action: 'mallUShopList'
},{
    mobile: '15606958460',
    api_token: 'd22160093310e86d538f652f57159eff',
},function(res) {
    // success
},function(error) {
    console.log(error);
});
Copy after login

The above is the detailed content of How to use ajax encapsulated function jsonp. For more information, please follow other related articles on the PHP Chinese website!

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