2012-03-14 57 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/