jQuery 如何?将附加参数传递给 $.ajax 调用的成功回调?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2602981/
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
jQuery HOW TO?? pass additional parameters to success callback for $.ajax call?
提问by dotnetgeek
I am trying, in vain it seems, to be able to pass additional parameters back to the success callback method that I have created for a successful ajax call. A little background. I have a page with a number of dynamically created textbox / selectbox pairs. Each pair having a dynamically assigned unique name such as name="unique-pair-1_txt-url" and name="unique-pair-1_selectBox" then the second pair has the same but the prefix is different.
我试图将额外的参数传递回我为成功的 ajax 调用创建的成功回调方法,但似乎是徒劳的。一点背景。我有一个页面,其中包含许多动态创建的文本框/选择框对。每对具有动态分配的唯一名称,例如 name="unique-pair-1_txt-url" 和 name="unique-pair-1_selectBox" 然后第二对具有相同但前缀不同。
In an effort to reuse code, I have crafted the callback to take the data and a reference to the selectbox. However when the callback is fired the reference to the selectbox comes back as 'undefined'. I read herethat it should be doable. I have even tried taking advantage of the 'context' option but still nothing. Here is the script block that I am trying to use:
为了重用代码,我精心设计了回调以获取数据和对选择框的引用。然而,当回调被触发时,对选择框的引用返回为“未定义”。我在这里读到它应该是可行的。我什至尝试利用“上下文”选项,但仍然一无所获。这是我尝试使用的脚本块:
<script type="text/javascript" language="javascript">
$j = jQuery.noConflict();
function getImages(urlValue, selectBox) {
$j.ajax({
type: "GET",
url: $j(urlValue).val(),
dataType: "jsonp",
context: selectBox,
success:function(data){
loadImagesInSelect(data)
} ,
error:function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
function loadImagesInSelect(data) {
var select = $j(this);
select.empty();
$j(data).each(function() {
var theValue = $j(this)[0]["@value"];
var theId = $j(this)[0]["@name"];
select.append("<option value='" + theId + "'>" + theValue + "</option>");
});
select.children(":first").attr("selected", true);
}
</script>
From what I have read, I feel I am close but I just cant put my finger on the missing link. Please help in your typical ninja stealthy ways. TIA
从我读到的内容来看,我觉得我很接近,但我无法将手指放在缺失的链接上。请以您典型的忍者隐身方式提供帮助。TIA
****UPDATE**** Nick is a true Ninja. They should invent a new badge for that! His answer below does the trick. As he mentions it's 1.4 specific but I can live with that. Here is my final code that is working for any Ninjas in training (and my future reference):
****更新**** 尼克是一个真正的忍者。他们应该为此发明一个新的徽章!他在下面的回答可以解决问题。正如他所提到的,它是 1.4 特定的,但我可以接受。这是我的最终代码,适用于任何正在接受培训的忍者(以及我未来的参考):
<script type="text/javascript" language="javascript">
$j = jQuery.noConflict();
function getImages(urlValue, selectBox) {
$j.ajax({
type: "GET",
url: urlValue+ '?callback=?',
dataType: "jsonp",
context: selectBox,
success: jQuery.proxy(function (data) {
var select = $j(this);
select.empty();
$j(data).each(function() {
var theValue = $j(this)[0]["@value"];
var theId = $j(this)[0]["@name"];
select.append("<option value='" + theId + "'>" + theValue + "</option>");
});
select.children(":first").attr("selected", true);
}, selectBox),
error:function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
</script>
采纳答案by Nick Craver
Updated:If you're using jQuery 1.4 use this to simplify things a bit:
更新:如果您使用 jQuery 1.4,请使用它来简化一些事情:
success: jQuery.proxy(function (data) {
var select = $j(this);
select.empty();
$j(data).each(function() {
var theValue = $j(this)[0]["@value"];
var theId = $j(this)[0]["@name"];
select.append("<option value='" + theId + "'>" + theValue + "</option>");
});
select.children(":first").attr("selected", true);
}, selectBox)
回答by ClayKaboom
This is what I did, and it also worked fine:
这就是我所做的,它也运行良好:
$.ajax('URL', {
myCustomControl: selectBox,
myCustomVariable: 'teste',
data:
{
myData: 1
},
success: function (data, textStats, jqXHR) {
myFunction(data, textStats, jqXHR, this.myCustomControl, this.myCustomVariable);
}
});
You can add controls and variables to the parameters of your ajax call.
您可以将控件和变量添加到 ajax 调用的参数中。
回答by Egor Pavlikhin
Put this into your $.ajax parameters.
把它放到你的 $.ajax 参数中。
invokedata: {
data1: "yourdata",
data2: "moredata"
}
In the success function use it like this
在成功函数中像这样使用它
this.invokedata.data1;
this.invokedata.data2;
Your $.ajax call and the success function must also be a part of the same object. Put your functions in an object and define them like this
您的 $.ajax 调用和成功函数也必须是同一对象的一部分。将您的函数放在一个对象中并像这样定义它们
function myObject {
var getImage = function(..) { }
var loadImagesInSelect = function(..) { }
}
回答by Hutch Moore
this
is Out of Scope
this
超出范围
Just so you (or anyone else) understand(s)1, the reason that this
was undefined in loadImagesInSelect()
in your original example was because that function was under a different scope, and scopes don't "cascade" like that2.
只是为了让您(或其他任何人)理解1,在您的原始示例中this
未定义的原因loadImagesInSelect()
是因为该函数在不同的范围内,并且范围不会像2那样“级联” 。
When you specified a "context" of selectBox
in your AJAX call, it set the context (this
) for the functions given to "success" and "error". (It just so happens that they were both anonymous functions.) At this point, this
is defined in both of these functions, as the value of selectBox
. Now, in the function passed to "success", you call loadImagesInSelect()
. When you call a function, it creates a new scope. In this scope, this
will be window
in non-strict mode and undefined
in strict mode.
当您selectBox
在 AJAX 调用中指定“上下文”时,它会this
为赋予“成功”和“错误”的函数设置上下文 ( )。(碰巧它们都是匿名函数。)此时,this
在这两个函数中都定义了 ,作为 的值selectBox
。现在,在传递给“成功”的函数中,您调用loadImagesInSelect()
. 当你调用一个函数时,它会创建一个新的作用域。在这个范围内,this
将window
处于非严格模式和undefined
严格模式。
Put Graphically (in Strict Mode3):
以图形方式放置(在严格模式3 中):
// this = window (global scope)
$j = jQuery.noConflict();
function getImages(urlValue, selectBox) {
// this = undefined (function scope level 1)
$j.ajax({
type: "GET",
url: $j(urlValue).val(),
dataType: "jsonp",
context: selectBox,
success: function(data) {
// this = selectBox (function scope level 2)
loadImagesInSelect(data);
},
error: function(xhr, ajaxOptions, thrownError) {
// this = selectBox (function scope level 2)
alert(xhr.status);
alert(thrownError);
}
});
}
function loadImagesInSelect(data) {
// this = undefined (function scope level 3)
var select = $j(this);
select.empty();
$j(data).each(function() {
var theValue = $j(this)[0]["@value"];
var theId = $j(this)[0]["@name"];
select.append("<option value='" + theId + "'>" + theValue + "</option>");
});
select.children(":first").attr("selected", true);
}
$.proxy()
is Redundant
$.proxy()
是冗余的
The use of $.proxy()
in your updated code is redundant. You use $.proxy()
to get this
to the function that was formerly called loadImagesInSelect()
, but you moved that function up into "success" anyway (instead of calling it from within "success"). It already has access now to the value of this
specified by "context".
使用$.proxy()
在更新的代码是多余的。您可以使用$.proxy()
来获取this
到以前调用的函数loadImagesInSelect()
,但你感动,功能成“成功”呢(而不是从“成功”中调用它)。它现在已经可以访问this
“上下文”指定的值。
You could remove the $.proxy()
wrapper around your "success" function in your updated code and it would still work.
您可以$.proxy()
在更新的代码中删除“成功”函数周围的包装器,它仍然可以工作。
I know it's been years since you asked your question, but I hope this helps.
我知道你问这个问题已经好几年了,但我希望这会有所帮助。
- I hope this doesn't come across as condescending; it's not meant to be.
- At least, not when you calla function, and not with context. If you define a function within a function (i.e. a closure), then any variables in the outer function will be available in the inner function. However, the outer function's context (the
this
variable) still isn't available in the inner function. - Replace
undefined
withwindow
for non-strict mode. - Or the native
Function.prototype.bind()
in ECMAScript 5.
- 我希望这不会让人觉得居高临下;它不应该是。
- 至少,不是在您调用函数时,也不是在上下文中。如果您在函数内定义函数(即闭包),则外部函数中的任何变量都将在内部函数中可用。但是,外部函数的上下文(
this
变量)在内部函数中仍然不可用。 - 更换
undefined
用window
非严格模式。 - 或者
Function.prototype.bind()
ECMAScript 5 中的原生。
回答by aecavac
You can use indexValueattribute for passing :
您可以使用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);
});