重新制作ajax功能

时间:2015-12-13 19:41:59

标签: javascript jquery ajax

有没有办法制作一个转换默认ajax函数的函数。

这是我有的ajax功能

$.ajax({
    type: "POST",
    url: "http://" + document.location.host + '/userajax',
    data: 'type=register&name=' + name,
    beforeSend:function() {

    },
    success: function(response) {

    }
});

这就是我希望它看起来像

ajax('url', {
    method: 'get',
    parameters: {
        name: $('#name').val()
    },
    beforeSend: function() {

    },
    success: function(transport) {

    }
});

我试图在互联网上搜索但没有找到任何东西

3 个答案:

答案 0 :(得分:1)

当然,您可以创建如下函数:

function ajax(url, params){

    // everything is now available here
    console.log( url ); // output: http://www.google.com

    // you can get the data of the params object like this
    console.log( params.method ); // output: get

    // you can execute the beforeSend like this:
    params.beforeSend();

    // additionally you might want to check everything.
    // maybe if the method is NOT set, you want it to always use GET
    switch(arguments.length) {
        case 1: url = throw new Error('Url should be set');
        case 2: params.method = 'get';
        case 3: break;
        default: throw new Error('illegal argument count')
    }

}

您可以这样称呼:

ajax('http://www.google.com', {
    method: 'get',
    parameters: {
        name: $('#name').val()
    },
    beforeSend: function() {
        // some function
    },
    success: function(transport) {
        // some function
    }
});

答案 1 :(得分:-1)

我不这么认为。但你可以这样做:

$(document).ready(function(){

    var parameters = {
            name:       $("#name").val(),
            desc:       $("#desc").val()

        };

        $.ajax({
            url: 'path/to/file',
            data : parameters,
            beforeSend: beforeSubmit,
            dataType: "json",
            type : 'POST',
        })
        .done(function(data) {


        })
        .fail(function() {
            console.log("error");
        })
    })

另请注意,我不会直接在通话中设置beforeSend的功能,我会创建一个externe功能,让我有更多的自由。

所以我可以这样做:

function beforeSubmit(){
   if(something !== 'somethingelse'){
       return false; //ajax call will stop
   }else{
       return true; //ajax call
   }
}

答案 2 :(得分:-1)

这当然是可能的,这只是一些工作。您需要的一些基础知识:

首先,您需要很好地理解XMLHTTPRequest API,您可以在MDN上找到有关该内容的更多信息。

接下来,了解如何进行回调,实际上非常简单,您可以将匿名函数引用作为函数的选项或属性传递。就是这样:

function doSomething(variable, callback){
  variable = variable + ' something'; // just doing something with the variable
  callback(variable);
}

// then call the function with a callback (anonymous function)
doSomething('doing', function(result){ alert(result); });

您应该收到一条提示“做某事'。

”的提醒

最后你应该知道如何阅读一个对象,作为'选项'在ajax函数中。假设你有这样的功能:

function foo(url, options){
  console.log(url);
  console.log(options.method);
  console.log(options.parameters.name);
}

// call it like this
foo('https://google.com/', {
    method: 'get',
    parameters: {
        name: 'myName'
    }
});

这应记录控制台中的url,方法和参数。

现在,从这里开始,你应该把所有的东西放在一起。祝你好运!