在jquery AJAX成功回调中传递变量到函数

时间:2022-12-08 20:25:33

I am trying to preload some images with a jQuery AJAX call, but am having real problems passing a (url) string into a function within the success function of the AJAX call (if that makes sense).

我正在尝试用jQuery AJAX调用预加载一些图像,但是在AJAX调用的success函数中(如果有意义的话)将(url)字符串传递给函数时遇到了真正的问题。

Here is my code as is stands:

我的代码如下:

//preloader for images on gallery pages
window.onload = function() {
    setTimeout(function() {     
        var urls = ["./img/party/"]; //just one to get started

        for ( var i = 0; i < urls.length; i++ ) {
            $.ajax({
                url: urls[i],
                success: function(data,url) {
                    $(data).find("a:contains(.jpg)").each(function(url) {                               
                        new Image().src = url + $(this).attr("href");
                    });
                }
            });
        };  
    }, 1000);
};

One can see my (failed) attempt at passing the url through into the .each() call - url ends up takes the value of increasing integers. Not sure why or what these relate to, maybe the number of jpg files?

可以看到我的(失败的)尝试将url传递到.each()调用——url结束了增加整数的值。不知道为什么或者这些与jpg文件的数量有关?

...anyway, it should of course take the single value in my original urls array.

…无论如何,它应该在我的原始url数组中取一个值。

Thanks for any help - I always seem to get in a bit of a twist with these callbacks.

感谢您的帮助——我似乎总是对这些回调感到困惑。


PROGESS?

进步吗?

So, I mucked around a bit, taking heed of comments from @ron tornambe and @PiSquared and am currently here:

所以,我有点乱了阵脚,留意了@ron tornambe和@PiSquared的评论,现在我在这里:

//preloader for images on gallery pages
window.onload = function() {
    var urls = ["./img/party/","./img/wedding/","./img/wedding/tree/"];

    setTimeout(function() {
        for ( var i = 0; i < urls.length; i++ ) {
            $.ajax({
                url: urls[i],
                success: function(data) {
                    image_link(data,i);
                    function image_link(data, i) {
                        $(data).find("a:contains(.jpg)").each(function(){ 
                            console.log(i);
                            new Image().src = urls[i] + $(this).attr("href");
                        });
                    }
                }
            });
        };  
    }, 1000);       
};

I tried putting the image_link(data, i) here there and everywhere (in each nested function etc.) but I get the same result: the value for i is only ever logged as 3. I suspect that this is because all references to i point to the same thing and by the time the asynchronous task actually gets to image_link(data, i) the for... loop is over and done with (and hence has a value of 3). Needless to say this gives urls[i] as 'undefined'.

我尝试将image_link(data, I)放在这里,并放在各处(在每个嵌套函数中等等),但得到的结果是一样的:I的值只被记录为3。我怀疑这是因为所有对I的引用都指向相同的东西,当异步任务实际到达image_link(data, I) for时……循环结束并结束(因此值为3)。不用说,这将给url [i]赋值为'undefined'。

Any (more) tips how I can get round this?

有什么(更多)建议可以让我避开这个问题吗?

7 个解决方案

#1


145  

I was just experiencing a similar issue, and believe I have found a solution.

我也遇到过类似的问题,我相信我找到了解决办法。

Since the settings object is tied to that ajax call, you can simply add in the indexer as a custom setting, which you can then access using this in the success callback:

由于settings对象与那个ajax调用绑定在一起,所以您只需将索引器作为自定义设置添加进来,然后您可以在success callback中使用它来访问:

//preloader for images on gallery pages
window.onload = function() {
    var urls = ["./img/party/","./img/wedding/","./img/wedding/tree/"];

    setTimeout(function() {
        for ( var i = 0; i < urls.length; i++ ) {
            $.ajax({
                url: urls[i],
                indexValue: i,
                success: function(data) {
                    image_link(data , this.indexValue);

                    function image_link(data, i) {
                        $(data).find("a:contains(.jpg)").each(function(){ 
                            console.log(i);
                            new Image().src = urls[i] + $(this).attr("href");
                        });
                    }
                }
            });
        };  
    }, 1000);       
};

Hopefully that does the trick.

希望这能奏效。

#2


7  

Try something like this (use this.url to get the url):

试试这个(用这个)。获取url的url):

$.ajax({
    url: 'http://www.example.org',
    data: {'a':1,'b':2,'c':3},
    dataType: 'xml',
    complete : function(){
        alert(this.url)
    },
    success: function(xml){
    }
});

Taken from here

从这里

#3


6  

You can't pass parameters like this - the success object maps to an anonymous function with one parameter and that's the received data. Create a function outside of the for loop which takes (data, i) as parameters and perform the code there:

不能像这样传递参数——success对象映射到带有一个参数的匿名函数,这就是接收到的数据。在for循环外部创建一个函数,该函数以(数据,i)为参数,并在其中执行代码:

function image_link(data, i) {
   $(data).find("a:contains(.jpg)").each(function(){                                
       new Image().src = url[i] + $(this).attr("href");
   }
}
...
success: function(data){
    image_link(data, i)
}

#4


5  

You can also use indexValue attribute for passing multiple parameters via object:

还可以使用indexValue属性通过对象传递多个参数:

var someData = "hello";

jQuery.ajax({
    url: "http://maps.google.com/maps/api/js?v=3",
    indexValue: {param1:someData, param2:"Other data 2", param3: "Other data 3"},
    dataType: "script"
}).done(function() {
    console.log(this.indexValue.param1);
    console.log(this.indexValue.param2);
    console.log(this.indexValue.param3);
}); 

#5


3  

I'm doing it this way:

我是这样做的:

    function f(data,d){
    console.log(d);
    console.log(data);
}
$.ajax({
    url:u,
    success:function(data){ f(data,d);  }
});

#6


0  

Just to share a similar problem I had in case it might help some one, I was using:

为了分享一个类似的问题,我曾经用过:

var NextSlidePage = $("bottomcontent" + Slide + ".html");

to make the variable for the load function, But I should have used:

为了使变量的负载函数,但我应该使用:

var NextSlidePage = "bottomcontent" + Slide + ".html";

without the $( )

没有(美元)

Don't know why but now it works! Thanks, finally i saw what was going wrong from this post!

不知道为什么,但现在可以了!谢谢,我终于看到这篇文章出了什么问题!

#7


0  

I've meet the probleme recently. The trouble is coming when the filename lenght is greather than 20 characters. So the bypass is to change your filename length, but the trick is also a good one.

我最近遇到了这个问题。当文件名lenght大于20个字符时,麻烦就来了。所以旁路是改变你的文件名长度,但技巧也是一个很好的方法。

$.ajaxSetup({async: false}); // passage en mode synchrone
$.ajax({
   url: pathpays,
   success: function(data) {
      //debug(data);
      $(data).find("a:contains(.png),a:contains(.jpg)").each(function() {
         var image = $(this).attr("href");
         // will loop through
         debug("Found a file: " + image);
         text +=  '<img class="arrondie" src="' + pathpays + image + '" />';
      });
      text = text + '</div>';
      //debug(text);
   }
});

After more investigation the trouble is coming from ajax request: Put an eye to the html code returned by ajax:

经过更多的调查,问题来自ajax请求:关注ajax返回的html代码:

<a href="Paris-Palais-de-la-cite%20-%20Copie.jpg">Paris-Palais-de-la-c..&gt;</a>
</td>
<td align="right">2015-09-05 09:50 </td>
<td align="right">4.3K</td>
<td>&nbsp;</td>
</tr>

As you can see the filename is splitted after the character 20, so the $(data).find("a:contains(.png)) is not able to find the correct extention.

正如您所看到的,文件名在字符20之后被分割,所以$(data).find(“a:contains(.png))不能找到正确的扩展。

But if you check the value of the href parameter it contents the fullname of the file.

但是如果您检查href参数的值,它将包含文件的全称。

I dont know if I can to ask to ajax to return the full filename in the text area?

我不知道是否可以要求ajax返回文本区域的完整文件名?

Hope to be clear

希望能清楚

I've found the right test to gather all files:

我找到了收集所有文件的正确测试:

$(data).find("[href$='.jpg'],[href$='.png']").each(function() {  
var image = $(this).attr("href");

#1


145  

I was just experiencing a similar issue, and believe I have found a solution.

我也遇到过类似的问题,我相信我找到了解决办法。

Since the settings object is tied to that ajax call, you can simply add in the indexer as a custom setting, which you can then access using this in the success callback:

由于settings对象与那个ajax调用绑定在一起,所以您只需将索引器作为自定义设置添加进来,然后您可以在success callback中使用它来访问:

//preloader for images on gallery pages
window.onload = function() {
    var urls = ["./img/party/","./img/wedding/","./img/wedding/tree/"];

    setTimeout(function() {
        for ( var i = 0; i < urls.length; i++ ) {
            $.ajax({
                url: urls[i],
                indexValue: i,
                success: function(data) {
                    image_link(data , this.indexValue);

                    function image_link(data, i) {
                        $(data).find("a:contains(.jpg)").each(function(){ 
                            console.log(i);
                            new Image().src = urls[i] + $(this).attr("href");
                        });
                    }
                }
            });
        };  
    }, 1000);       
};

Hopefully that does the trick.

希望这能奏效。

#2


7  

Try something like this (use this.url to get the url):

试试这个(用这个)。获取url的url):

$.ajax({
    url: 'http://www.example.org',
    data: {'a':1,'b':2,'c':3},
    dataType: 'xml',
    complete : function(){
        alert(this.url)
    },
    success: function(xml){
    }
});

Taken from here

从这里

#3


6  

You can't pass parameters like this - the success object maps to an anonymous function with one parameter and that's the received data. Create a function outside of the for loop which takes (data, i) as parameters and perform the code there:

不能像这样传递参数——success对象映射到带有一个参数的匿名函数,这就是接收到的数据。在for循环外部创建一个函数,该函数以(数据,i)为参数,并在其中执行代码:

function image_link(data, i) {
   $(data).find("a:contains(.jpg)").each(function(){                                
       new Image().src = url[i] + $(this).attr("href");
   }
}
...
success: function(data){
    image_link(data, i)
}

#4


5  

You can also use indexValue attribute for passing multiple parameters via object:

还可以使用indexValue属性通过对象传递多个参数:

var someData = "hello";

jQuery.ajax({
    url: "http://maps.google.com/maps/api/js?v=3",
    indexValue: {param1:someData, param2:"Other data 2", param3: "Other data 3"},
    dataType: "script"
}).done(function() {
    console.log(this.indexValue.param1);
    console.log(this.indexValue.param2);
    console.log(this.indexValue.param3);
}); 

#5


3  

I'm doing it this way:

我是这样做的:

    function f(data,d){
    console.log(d);
    console.log(data);
}
$.ajax({
    url:u,
    success:function(data){ f(data,d);  }
});

#6


0  

Just to share a similar problem I had in case it might help some one, I was using:

为了分享一个类似的问题,我曾经用过:

var NextSlidePage = $("bottomcontent" + Slide + ".html");

to make the variable for the load function, But I should have used:

为了使变量的负载函数,但我应该使用:

var NextSlidePage = "bottomcontent" + Slide + ".html";

without the $( )

没有(美元)

Don't know why but now it works! Thanks, finally i saw what was going wrong from this post!

不知道为什么,但现在可以了!谢谢,我终于看到这篇文章出了什么问题!

#7


0  

I've meet the probleme recently. The trouble is coming when the filename lenght is greather than 20 characters. So the bypass is to change your filename length, but the trick is also a good one.

我最近遇到了这个问题。当文件名lenght大于20个字符时,麻烦就来了。所以旁路是改变你的文件名长度,但技巧也是一个很好的方法。

$.ajaxSetup({async: false}); // passage en mode synchrone
$.ajax({
   url: pathpays,
   success: function(data) {
      //debug(data);
      $(data).find("a:contains(.png),a:contains(.jpg)").each(function() {
         var image = $(this).attr("href");
         // will loop through
         debug("Found a file: " + image);
         text +=  '<img class="arrondie" src="' + pathpays + image + '" />';
      });
      text = text + '</div>';
      //debug(text);
   }
});

After more investigation the trouble is coming from ajax request: Put an eye to the html code returned by ajax:

经过更多的调查,问题来自ajax请求:关注ajax返回的html代码:

<a href="Paris-Palais-de-la-cite%20-%20Copie.jpg">Paris-Palais-de-la-c..&gt;</a>
</td>
<td align="right">2015-09-05 09:50 </td>
<td align="right">4.3K</td>
<td>&nbsp;</td>
</tr>

As you can see the filename is splitted after the character 20, so the $(data).find("a:contains(.png)) is not able to find the correct extention.

正如您所看到的,文件名在字符20之后被分割,所以$(data).find(“a:contains(.png))不能找到正确的扩展。

But if you check the value of the href parameter it contents the fullname of the file.

但是如果您检查href参数的值,它将包含文件的全称。

I dont know if I can to ask to ajax to return the full filename in the text area?

我不知道是否可以要求ajax返回文本区域的完整文件名?

Hope to be clear

希望能清楚

I've found the right test to gather all files:

我找到了收集所有文件的正确测试:

$(data).find("[href$='.jpg'],[href$='.png']").each(function() {  
var image = $(this).attr("href");