2012-03-14 8 views
4

次のコードは、 'undefined'を警告し、期待どおりに応答データから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あなたのコードで警告しますが、私はあなたの "警告"があなたがajaxの要求より速く実行されると思っていますので、ajaxの結果を警告しようとしているときには、この時点でajaxが終了していないので、 –

答えて

9
  1. HTTPメソッドがtypeはなくmethodによってで指定されているので、あなたが使用する必要があります;

    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/

関連する問題