我在尝试将额外的参数传递给我为成功的ajax调用创建的success回调方法,但似乎徒劳无功。背景是这样的:我有一个页面,其中有许多动态创建的文本框/选择框对,每个对都有一个动态分配的唯一名称,例如name="unique-pair-1_txt-url"和name="unique-pair-1_selectBox",然后第二对具有相同的前缀。
为了重复使用代码,我编写了回调函数来处理数据和选择框的引用。但是,当回调函数被触发时,对选择框的引用返回为'undefined'。我在这里读到此处可以实现。我甚至尝试利用“context”选项,但仍然没有结果。下面是我正在尝试使用的脚本块:
<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>
根据我所了解的,我觉得我离答案很近,但就是找不到关键点。请以你们惯有的忍者隐秘方式帮助我。TIA
****更新**** Nick是一个真正的忍者。他们应该为此发明一个新徽章!他下面的答案解决了我的问题。虽然他提到它只适用于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>
getImages(urlValue, selectBox)
的代码段? - Anurag$j('[name=.selImageList]'))
有效吗?根据代码,在 ajax 调用期间如果没有任何更改,selectBox
应该按预期工作。尝试在不同的点记录selectBox
并检查问题是否在成功回调函数、loadImagesInSelect
函数或甚至是getImages
函数中未定义。 - Anurag