2009-11-17 1 views
1

Мне нужно сделать вызов Ajax и получить ответное обновление дочернего элемента DOM, который был нажат, чтобы вызвать событие. Пример HTML:Как сохранить контекст через вызов Ajax

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

Sample 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 
        } 
       }); 
      }); 
     } 
    ); 
}); 

На проблемной линии "это" относится к объекту ответа Ajax. Я не знаю, как сохранить «этот» контекст из нескольких строк выше, поэтому я могу обновить его содержимое с ответом на вызов Ajax.

ответ

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 
        } 
       }); 
      }); 
     } 
    ); 
}); 
+0

Это именно то, чего мне не хватало. Так просто, спасибо. – Michael

+1

Не забудьте добавить «var» перед частью «myData = ...», чтобы предотвратить ее объявление как глобальной переменной. Кроме того, если вы предоставляете функцию $ .ajax() параметром «datatype: 'json», вам не нужно будет использовать JSON.parse для анализа результатов. –

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