2012-03-14 22 views
4

以下代碼警告'未定義',並且不會像我期望的那樣從響應數據中追加html。有誰知道爲什麼?jsFiddle測試jQuery與回聲的AJAX請求

JavaScript的:

$(function() { 

    $('.document').on('click', '.ajax', function(e) { 
     e.preventDefault(); 

     // ajax request 
     $.ajax({ 
      async: true, 
      cache: false, 
      type: 'post', 
      url: '/echo/html/', 
      data: { 
       html: '<p>This is echoed the response in HTML format</p>', 
       delay: 1 
      }, 
      dataType: 'html', 
      beforeSend: function() { 
       console.log('Fired prior to the request'); 
      }, 
      success: function(data) { 
       console.log('Fired when the request is successfull'); 
       $('.document').append(data); 
      }, 
      complete: function() { 
       console.log('Fired when the request is complete'); 
      } 
     }); 

    }); 

});​ 

HTML:

<div class="document"> 
    <a class="ajax" href="#">Fire an AJAX request</a> 
</div>​ 

實施例的jsfiddle:http://jsfiddle.net/L6bJ2/3/

+0

有n o在代碼中提醒,但我認爲你的「alert」執行得比你的ajax請求更快,所以當你試圖提醒ajax結果時,有沒有,因爲ajax在這一點上沒有完成。 – 2012-03-14 11:06:12

回答

9
  1. 與由type而非method指定的HTTP方法,所以應該使用;

    type: 'post', 
    
  2. 因爲您所指定的響應類型爲HTML,你在success回調data參數傳遞的字符串;但它看起來像你正在試圖使用data.html期待JSON。相反,直接使用data;

    success: function(data) { 
        console.log('Fired when the request is successfull'); 
        $('.document').append(data); 
    }, 
    

有了這些變化,你會發現it works: http://jsfiddle.net/L6bJ2/6/