简体   繁体   English

将参数传递给ajax回调

[英]pass a parameter to an ajax callback

I have a javascript function which must get a file and pass it with another parameter: 我有一个javascript函数,该函数必须获取一个文件并将其与另一个参数一起传递:

getJsonFile = function(fileName, callback, error, data) {
        var ajaxOptions = {
            url: util.pathJoin([Options.server_cache_path, jsonRelativeFileName]),
            type: "GET",
            dataType: "json",
            success: function(album) {
                callback(album, data)
            },
            error: error
        };

The getJsonFile function is called many times in for cycles throughout the application. 在整个应用程序中for多次调用getJsonFile函数for循环。

However, in the callback function, I sometimes find that the value of data is altered... Why does it happen? 但是,在callback函数中,有时会发现data的值已更改...为什么会发生? What's the solution? 有什么解决方案?

As you described above, you are calling getJsonFile function from a loop (for) and most likely passing the data parameter as reference. 如上所述,您正在从循环(用于)中调用getJsonFile函数,并且很可能将data参数作为引用传递。 In that scenario, you are passing a pointer to a variable which is changing in every loop iteration and by the time the success callback is invoked, data parameter has a reference to a different object from the original call. 在这种情况下,您将传递一个指向变量的指针,该变量在每次循环迭代中都会更改,并且在调用成功回调时, data参数将引用与原始调用不同的对象。

One way to fix this kind of problems is to make copies of the parameters you received (or at least from data ) OR capture the value you are interested in using a closure to capture the current data referenced value. 解决此类问题的一种方法是复制收到的参数(或至少从data中复制) 使用闭包捕获当前数据引用值来捕获您感兴趣的值。

getJsonFile = function(fileName, callback, error, data) {
        var callbackCall = (function(myData) { 
            return function(myAlbum) { callback(myAlbum, myData); };
        })(data);
        var ajaxOptions = {
            url: util.pathJoin([Options.server_cache_path, jsonRelativeFileName]),
            type: "GET",
            dataType: "json",
            success: function(album) {
                callbackCall(album);
            },
            error: error
        };

Avoiding the callbackCall variable 避免使用callbackCall变量

getJsonFile = function(fileName, callback, error, data) {
   // Code omitted...
   success: (function(myData) { 
            return function(album) { callback(album, myData); };
   })(data)
   // Code omitted...
}

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

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