jQuery如何?将附加参数传递给$ .ajax调用的成功回调?

时间:2022-12-08 19:39:07

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 here that 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:

为了重用代码,我精心设计了回调来获取数据和对selectbox的引用。但是,当回调被触发时,对selectbox的引用将返回为“undefined”。我在这里读到它应该是可行的。我甚至尝试过利用'上下文'选项,但仍然没有。这是我尝试使用的脚本块:

<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,但我可以忍受。这是我的最终代码,适用于任何Ninjas的培训(以及我未来的参考):

<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>

5 个解决方案

#1


12  

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)

#2


22  

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调用的参数中。

#3


12  

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调用和success函数也必须是同一对象的一部分。将您的函数放在一个对象中并像这样定义它们

function myObject {
    var getImage = function(..) { }
    var loadImagesInSelect = function(..) { }
}

#4


3  

this is Out of Scope

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,原始示例中loadImagesInSelect()中未定义的原因是因为该函数在不同的范围内,并且范围不像那样“级联”。

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.

当您在AJAX调用中指定selectBox的“上下文”时,它会为给定为“success”和“error”的函数设置上下文(this)。 (恰好它们都是匿名函数。)此时,这是在这两个函数中定义的,作为selectBox的值。现在,在传递给“success”的函数中,调用loadImagesInSelect()。调用函数时,它会创建一个新范围。在此范围内,这将是非严格模式下的窗口,严格模式下未定义。


Put Graphically (in Strict Mode3):

// 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

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()来获得以前称为loadImagesInSelect()的函数,但是无论如何你都将该函数移动到“成功”(而不是在“成功”中调用它)。它现在已经可以访问“context”指定的值。

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.

我知道你提出问题已有好几年了,但我希望这会有所帮助。


  1. I hope this doesn't come across as condescending; it's not meant to be.
  2. 我希望这不会像居高临下一样;它并不意味着。
  3. At least, not when you call a 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.
  4. 至少,不是在你调用函数时,而不是在调用上下文时。如果在函数内定义函数(即闭包),那么外部函数中的任何变量都将在内部函数中可用。但是,外部函数的上下文(this变量)仍然在内部函数中不可用。
  5. Replace undefined with window for non-strict mode.
  6. 对于非严格模式,将窗口替换为undefined。
  7. Or the native Function.prototype.bind() in ECMAScript 5.
  8. 或ECMAScript 5中的原生Function.prototype.bind()。

#5


0  

You can use indexValue attribute 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);
}); 

#1


12  

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)

#2


22  

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调用的参数中。

#3


12  

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调用和success函数也必须是同一对象的一部分。将您的函数放在一个对象中并像这样定义它们

function myObject {
    var getImage = function(..) { }
    var loadImagesInSelect = function(..) { }
}

#4


3  

this is Out of Scope

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,原始示例中loadImagesInSelect()中未定义的原因是因为该函数在不同的范围内,并且范围不像那样“级联”。

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.

当您在AJAX调用中指定selectBox的“上下文”时,它会为给定为“success”和“error”的函数设置上下文(this)。 (恰好它们都是匿名函数。)此时,这是在这两个函数中定义的,作为selectBox的值。现在,在传递给“success”的函数中,调用loadImagesInSelect()。调用函数时,它会创建一个新范围。在此范围内,这将是非严格模式下的窗口,严格模式下未定义。


Put Graphically (in Strict Mode3):

// 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

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()来获得以前称为loadImagesInSelect()的函数,但是无论如何你都将该函数移动到“成功”(而不是在“成功”中调用它)。它现在已经可以访问“context”指定的值。

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.

我知道你提出问题已有好几年了,但我希望这会有所帮助。


  1. I hope this doesn't come across as condescending; it's not meant to be.
  2. 我希望这不会像居高临下一样;它并不意味着。
  3. At least, not when you call a 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.
  4. 至少,不是在你调用函数时,而不是在调用上下文时。如果在函数内定义函数(即闭包),那么外部函数中的任何变量都将在内部函数中可用。但是,外部函数的上下文(this变量)仍然在内部函数中不可用。
  5. Replace undefined with window for non-strict mode.
  6. 对于非严格模式,将窗口替换为undefined。
  7. Or the native Function.prototype.bind() in ECMAScript 5.
  8. 或ECMAScript 5中的原生Function.prototype.bind()。

#5


0  

You can use indexValue attribute 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);
});