jsFiddle使用echo测试jQuery AJAX请求

时间:2012-03-14 11:02:20

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

    });

});​

HTML:

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

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

2 个答案:

答案 0 :(得分:9)

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

    type: 'post',
    
  2. 因为您已将响应类型指定为HTML,所以您将获得data回调的success参数中传递的字符串;但是当你尝试使用data.html时,你似乎期待JSON。相反,直接使用data;

    success: function(data) {
        console.log('Fired when the request is successfull');
        $('.document').append(data);
    },
    
  3. 通过这些更改,您会找到it works: http://jsfiddle.net/L6bJ2/6/

答案 1 :(得分:0)

现场示例在这里 https://stackoverflow.com/a/34940340/5361795

在ajax调用中使用beforeSend或完成回调函数,

来源ShoutingCode