如何在JQuery Ajax beforeSend函数中使用$(this).val()?

时间:2012-05-14 13:49:13

标签: jquery ajax post

我认为这很简单。我有一个工作的AJAX Jquery脚本,它将数据发布到另一个页面。我想在包含输入的分区中添加一个预加载器,每个输入都有一个带有id的类名。

我需要知道如何在beforeSend函数中使用post数据。

$('#stock_ctrl input').change(function() {

        $.ajax({
            type: "POST",
            data:   {   stock: this.value, 
                        id: this.name
                    },
            url: "example.php",

            beforeSend: function(data) {

                $('.updating'+data.id).html("Preloader here.");

               // I have tried data.id, this.name, $(this).attr.("name");

            success: function(){
                // success (this works fine)
            }
        });

    });

在代码中查看我的评论,这是我想要使用来自原始输入的名称数据的地方,这就是我所坚持的。任何帮助非常感谢。

3 个答案:

答案 0 :(得分:1)

在发送ajax之前定义$(this),例如:

$('#stock_ctrl input').change(function() {  
var self = $(this);

    $.ajax({
        type: "POST",
        data:   {   stock: self.val(), 
                    id: self.attr('name')
                },
        url: "example.php",
        beforeSend: function(data) {
            $('.updating'+data.id).html("Preloader here.");
           // I have tried data.id, this.name, self.attr.("name");
        success: function(){
            // success (this works fine)
        }
    });
});

应该做的工作:)

答案 1 :(得分:1)

当beforeSend的匿名函数正在执行时,您切换上下文,因此this不再引用同一个对象。 您需要提供您想要的this功能

$('#stock_ctrl input').change(function() {

    $.ajax({
        type: "POST",
        data:   {   stock: this.value, 
                    id: this.name
                },
        url: "example.php",

        beforeSend: $.proxy(function(data) {

           // this should now refer to the correct object and you can perform your operations
        }, this),
        success: function(){
            // success (this works fine)
        }
    });

});

刚输入但应该有效

答案 2 :(得分:0)

这应该做到

$('#stock_ctrl input').change(function() {
    var myVar = $(this);
    $.ajax({
        type: 'post',
        data: {
            stock: myVar.val(),
            id: myVar.attr('name')
        },
        url: 'example.php',
        beforeSend: function(data) {
            //do anything with myVar
        },
        success: function(){
            //do anything with myVar
        }
    });
});