jsFiddle使用echo测试jQuery AJAX请求

Rya*_*P13 4 ajax jquery

以下代码警告"未定义",并且不会像我预期的那样在响应数据中附加html.有谁知道为什么?

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

    });

});?
Run Code Online (Sandbox Code Playgroud)

HTML:

<div class="document">
    <a class="ajax" href="#">Fire an AJAX request</a>
</div>?
Run Code Online (Sandbox Code Playgroud)

示例jsFiddle:http://jsfiddle.net/L6bJ2/3/

Mat*_*att 9

  1. HTTP方法是使用type而不是method,因此您应该使用;

    type: 'post',
    
    Run Code Online (Sandbox Code Playgroud)
  2. 因为您已将响应类型指定为HTML,所以您将获得datasuccess回调参数中传递的String ; 但看起来你正在尝试使用JSON data.html.相反,data直接使用;

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

通过这些更改,您会发现它有效:http://jsfiddle.net/L6bJ2/6/