简化JavaScript中的jQuery Ajax调用

简化JavaScript中的jQuery Ajax调用//iterate thru the parameters arrays to compose the parameter data strin

大家好,欢迎来到IT知识分享网。简化JavaScript中的jQuery

在日常工作中(主要使用ASP.net),我需要编写很多JavaScript代码。我做的最重复的任务之一是jQuery Ajax调用。你看:

$.ajax({
    type: "POST",
    url: "MyPage.aspx/MyWebMethod",
    data: "{parameter:value,parameter:value}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        //function called successfull
    },
    error: function(msg) {
        //some error happened
    }
});

我不知道对您来说是否相同,但是对我来说用这种语法编写调用太麻烦了。而且,以前必须按照已知规则使用参数构建字符串以传递给WebMethod:字符串必须用引号传递,数字不能传递,等等。
因此,我决定创建一个小而有用的JavaScript类来帮助我有了这个特定的问题,现在我已经完成了jQuery Ajax调用,这对我来说非常友好。
在类构造函数中,我传递页面名称,方法名称以及成功和错误函数。以后,我会根据需要对addParam方法进行尽可能多的调用。最后,我调用run方法进行Ajax调用。成功函数和错误函数必须分别编写。
参数根据其类型进行处理。如果参数是字符串,则使用引号。如果是数字,我不会。日期参数是一种特殊情况。在这种情况下,我使用JavaScript日期对象的getTime()函数,该函数给了我自1970年1月1日以来的日期的毫秒数。后来,我将该值转换为UTC时间,这样我得到了一个最终的毫秒数,即我可以将Int64值传递给我的VB.net(或C#)代码,用它来重建.Net中的日期值。
这是我的jAjax类的完整列表(末尾带有日期帮助器功能):

function jAjax(pageName, methodName, successFunc, errorFunc) {
    //stores the page name
    this.pageName = pageName;
    //stores the method name
    this.methodName = methodName;
    //stores the success function
    this.successFunc = successFunc;
    //stores the error function
    this.errorFunc = errorFunc;
    //initializes the parameter names array
    this.paramNames = new Array();
    //initializes the parameter values array
    this.paramValues = new Array();

    //method for add a new parameter (simply pushes to the names and values arrays)
    this.addParam = function(name, value) {
        this.paramNames.push(name);
        this.paramValues.push(value);
    }

    //method to run the jQuery ajax request
    this.run = function() {
    //initializes the parameter data string
        var dataStr = '{';
        //iterate thru the parameters arrays to compose the parameter data string
        for (var k = 0; k < this.paramNames.length; k++) {
            //append the parameter name
            dataStr += this.paramNames[k] + ':';
            if (typeof this.paramValues[k] == 'string') {
                //string parameter, append between quotes
                dataStr += '"' + this.paramValues[k] + '",';
            } else if (typeof this.paramValues[k] == 'number') {
                //number parameter, append "as-is" calling toString()
                dataStr += this.paramValues[k].toString() + ',';
            } else if (typeof this.paramValues[k] == 'object') {
                if (this.paramValues[k].getTime != undefined) {
                    //date value
                    //call to my getUtcTime function to get the number of
                    //milliseconds (since january 1, 1970) in UTC format
                    //and append as a number
                    dataStr += getUtcTime(this.paramValues[k]).toString() + ',';
                } else {
                    //object value
                    //because I don't know what's this, append the toString()
                    //output
                    dataStr += '"' + this.paramValues[k].toString() + '",';
                }
            }
        }
        //if some parameter added, remove the trailing ","
        if (dataStr.length > 1) dataStr = dataStr.substr(0, dataStr.length - 1);
        //close the parameter data string
        dataStr += '}';

        //do the jQuery ajax call, using the parameter data string
        //and the success and error functions
        $.ajax({
            type: "POST",
            url: this.pageName + "/" + this.methodName,
            data: dataStr,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                successFunc(msg);
            },
            error: function(msg) {
                errorFunc(msg);
            }
        });
    }
}

function getUtcTime(dateValue) {
    //get the number of milliseconds since january 1, 1970
    var time = dateValue.getTime();
    //get the UTC time offset in minutes. if you created your date with
    //new Date(), maybe this contains a value. but if you compose the date
    //by yourself (i.e. var myDate = new Date(1984,5,21,12,53,11)) this will
    //be zero
    var minutes = dateValue.getTimezoneOffset() * -1;
    //get the milliseconds value
    var ms = minutes * 60000;
    //add to the original milliseconds value so we get the GMT exact value
    return time + ms;
}

这是使用的语法:

var ajaxCall = new jAjax('MyPage.aspx','MyWebMethod',successFunc,errorFunc);
ajaxCall.addParam('s','this is a string');
ajaxCall.addParam('n',34);
ajaxCall.addParam('d',new Date());
ajaxCall.run();

function successFunc(msg) {
    ...
}

function errorFunc(msg) {
}

另外一个好处是,您可以将成功和错误功能重新用于几个ajax调用。
希望对您有帮助!!随时在您的应用程序中使用jAjax类。

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/55657.html

(0)
上一篇 2024-05-04 17:57
下一篇 2024-05-04 21:11

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信