简体   繁体   English

我可以在ajax错误调用中使用变量而不是函数名称吗?

[英]Can I use a variable in an ajax error call instead of the Function name?

I have an Ajax call that works fine, but I am now trying to polish the code a bit 我有一个可以正常工作的Ajax调用,但是我现在尝试稍微完善一下代码

                $.ajax({
                url: wbURL,
                dataType: "xml",
                contentType: "text/xml; charset=\"utf-8\"",
                type: "POST",
                headers: '@"HEADER DATA',
                data: dataPacket,

                success: dealWithResonse,

                error: dealWithError
            });

what I am now trying to do is replace the success and error function names with variables so I can use it for other jobs. 我现在想做的是用变量替换成功和错误函数的名称,这样我就可以将其用于其他工作。

var SuccessFunctionCall =  dealWithResonse;                      
var ErrorFunctionCall = dealWithError;

                $.ajax({
                url: wbURL,
                dataType: "xml",
                contentType: "text/xml; charset=\"utf-8\"",
                type: "POST",
                headers: '@"HEADER DATA',
                data: dataPacket,

                success: SuccessFunctionCall,

                error: ErrorFunctionCall
            });

But my program stops at this point, assumingly as it can't find a function called ErrorFunctionCall. 但是我的程序到此为止停止了,大概是因为它找不到名为ErrorFunctionCall的函数。

can I use a variables vaule instead of an actual function name? 我可以使用变量值代替实际的函数名称吗?

Thank you in advance 先感谢您

You may define those functions as global and assign them to what you want: 您可以将这些函数定义为全局函数,并将其分配给所需的函数:

var SuccessFunctionCall = function(){dealWithResonse()};
var ErrorFunctionCall = function(){dealWithError()};

and call them as members of window: 并将它们称为window的成员:

success: window[SuccessFunctionCall](),
error: window[ErrorFunctionCall]()

Finally I have to say that I am not sure why you want to assign functions to variable names. 最后,我不得不说我不确定为什么要将函数分配给变量名。 You may define those functions directly and call them as you need. 您可以直接定义这些函数并根据需要调用它们。

You should define those functions in your variables as shown below: 您应该在变量中定义这些函数,如下所示:

 $(document).ready(function(){ var SuccessFunctionCall = function dealWithResonse(){ console.log("success"); }; var ErrorFunctionCall = function dealWithError(){ console.log("error"); }; $.ajax({ url: 'http:test', dataType: "xml", contentType: "text/xml; charset=\\"utf-8\\"", type: "POST", headers: '@"HEADER DATA', data: '', success: SuccessFunctionCall, error: ErrorFunctionCall }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> 
Try this 尝试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM