Miaolegemie / steamer-net

ajax util

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

steamer-net

NPM Version Travis Deps Coverage

ajax util for development

Options

  • url
    • [String] request url
  • param
    • [Object]
    • jsonCbName [String] necessary if ajaxType is JSONP
  • success
    • [Function] success callback
  • error
    • [Function] error callback
    • errCode: -1 => xhr.onerror, -2 => xhr.ontimeout
  • ajaxType
    • [String] ajax type
    • default GET
    • POST | GET | JSONP | FORM
  • dataType
    • [String] returned data type
    • default json
    • json | text |
  • xhrFields
    • [Object]
    • { withCredentials: true or false }
  • headers
    • [Object] request headers
    • { 'Access-Control-Allow-Origin': '*' }

Functions

  • net.ajaxInit
net.ajaxInit({
    beforeRequest: function(opts) {
        opts.param.xsrf = 'xsrf';
        return opts;
    },
    beforeResponse: function(data, successCb, errorCb) {
        data.foo = 'bar';
        successCb(data);
    },
    dataReturnSuccessCondition: function(data) {
        return !data.errCode;
    },
});

dataReturnSuccessCondition will invoked after beforeResponse

  • net.ajax
net.ajax({
    url: baseUrl + "get_material_info.fcg",
    param: {
    	id: 1
    },
    ajaxType: 'POST',
    success: function(data){
       	// some code
    },
    error: function(xhr){
    	// some code
    }
});
  • net.ajaxGet
net.ajaxGet({
    url: baseUrl + "get_material_info.fcg",
    param: {
    	id: 1
    },
    success: function(data){
       	// some code
    },
    error: function(xhr){
    	// some code
    }
});
  • net.ajaxPost
net.ajaxPost({
    url: baseUrl + "get_material_info.fcg",
    param: {
    	id: 1
    },
    success: function(data){
       	// some code
    },
    error: function(xhr){
    	// some code
    }
})
  • net.ajaxJsonp
net.ajaxJsonp({
    url: baseUrl + "get_material_info.fcg",
    param: {
    	id: 1,
    	jsonCbName: "jsonpCb"
    },
    success: function(data){
       	// some code
    },
    error: function(xhr){
    	// some code
    }
})

Local data

If you would like to use local data, you can specify localData param.

net.ajaxPost({
    url: baseUrl + "get_material_info.fcg",
    param: {
        id: 1
    },
    localData: [{id: 1, name: "a"}],
    success: function(data){
        // some code
    },
    error: function(xhr){
        // some code
    }
})

Test

npm run test

Changelog

  • v0.2.4 basic ajax features
  • v0.2.5 remove xhr.onload
  • v0.2.6 fix ajax get bug
  • v1.0.0 add tests
  • v1.1.1 fix xhr bug if you pass data to localData
  • v1.1.2 compatible with global
  • v1.1.4 add headers, xhrFields fields and support FORM type
  • v1.1.5 add beforeRequest and beforeResponse hooks

About

ajax util

License:MIT License


Languages

Language:JavaScript 99.5%Language:HTML 0.5%Language:CSS 0.0%