如何在Ajax调用中保留上下文

时间:2009-11-17 19:22:57

标签: javascript ajax jquery

我需要进行Ajax调用并让响应更新被单击以触发事件的DOM元素的子元素。示例HTML:

<div class="divClass">
  <p class="pClass1">1</p>
  <p class="pClass2">Some text.</p>
</div>
<div class="divClass">
  <p class="pClass1">2</p>
  <p class="pClass2">Some text.</p>
</div>
<div class="divClass">
  <p class="pClass1">3</p>
  <p class="pClass2">Some text.</p>
</div>

示例javascript代码:

$(document).ready(function(){
    $(".divClass").each(
        function(e) {
            $(this).attr('divValue', $('p.pClass1', this).text());
            $('p.pClass1', this).text('?');

            $(this).click(function(e) {
                e.preventDefault();

                $.ajax({
                    type: "POST",
                    url: "ajax.php",
                    data: "val=" + $(this).attr('divValue'),
                    success: function(msg) {
                        myData = JSON.parse(msg);
                        $('p.pClass1', this).html(myData.results[0]); // problem exists here
                    }
                });
            });
        }
    );
});

在问题行上“this”指的是Ajax响应对象。我不知道如何保留上面几行的“this”上下文,所以我可以用Ajax调用的响应来更新它的内容。

2 个答案:

答案 0 :(得分:3)

关闭!

$(document).ready(function(){
    $(".divClass").each(
        function(e) {
            $(this).attr('divValue', $('p.pClass1', this).text());
            $('p.pClass1', this).text('?');

            $(this).click(function(e) {
                e.preventDefault();

                // Store 'this' locally so it can be closed
                // by the function scope below
                var self = this;

                $.ajax({
                    type: "POST",
                    url: "ajax.php",
                    data: "val=" + $(this).attr('divValue'),
                    success: function(msg) {
                        myData = JSON.parse(msg);

                        // Now used your closed variable here
                        $('p.pClass1', self).html(myData.results[0]); // problem exists here
                    }
                });
            });
        }
    );
});

答案 1 :(得分:1)

var self = this;
$.ajax({ ..., success: function (msg) { ... $('p.pClass1', self) ... } ...