将变量传递给 jquery AJAX 成功回调中的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18413969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass variable to function in jquery AJAX success callback
提问by Jon
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 调用预加载一些图像,但是在将 (url) 字符串传递到 AJAX 调用的成功函数中的函数时遇到了真正的问题(如果有道理的话)。
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.
...无论如何,它当然应该采用我原始 urls 数组中的单个值。
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)。不用说,这给出urls[i]
了“未定义”。
Any (more) tips how I can get round this?
任何(更多)提示我如何解决这个问题?
回答by Paul Zaczkowski
Since the settings object is tied to that ajax call, you can simply add in the indexer as a custom property, which you can then access using this
in the success callback:
由于设置对象与该 ajax 调用相关联,您可以简单地将索引器添加为自定义属性,然后您可以this
在成功回调中使用该属性进行访问:
//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);
};
Edit:Adding in an updated JSFiddle example, as they seem to have changed how their ECHO endpoints work: https://jsfiddle.net/djujx97n/26/.
编辑:添加更新的 JSFiddle 示例,因为他们似乎改变了他们的 ECHO 端点的工作方式:https://jsfiddle.net/djujx97n/26/ 。
To understand how this works see the "context" field on the ajaxSettings object: http://api.jquery.com/jquery.ajax/, specifically this note:
要了解这是如何工作的,请参阅 ajaxSettings 对象上的“上下文”字段:http://api.jquery.com/jquery.ajax/ ,特别是此注释:
"The
this
reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves."
“
this
所有回调中的引用是在设置中传递给 $.ajax 的上下文选项中的对象;如果未指定上下文,则这是对 Ajax 设置本身的引用。”
回答by aecavac
You can also use indexValueattribute 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);
});
回答by Felipe Pereira
回答by PiSquared
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:
你不能像这样传递参数 - 成功对象映射到一个带有一个参数的匿名函数,这就是接收到的数据。在 for 循环之外创建一个函数,它将(data, 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)
}
回答by Nassim Aouragh
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); }
});
回答by megaten
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.
我最近遇到了问题。当文件名长度大于 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..></a>
</td>
<td align="right">2015-09-05 09:50 </td>
<td align="right">4.3K</td>
<td> </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");
回答by Alex
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!
不知道为什么,但现在它起作用了!谢谢,我终于看到这篇文章出了什么问题!