【问题标题】:jsFiddle testing jQuery AJAX request with echojsFiddle 使用 echo 测试 jQuery AJAX 请求
【发布时间】:2012-03-14 11:02:20
【问题描述】:

以下代码警告“未定义”,而不是按照我的预期从响应数据中附加 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/

【问题讨论】:

  • 您的代码中没有警报,但我认为您的“警报”执行速度比您的 ajax 请求快,所以当您尝试提醒 ajax 结果时,没有,因为 ajax 没有到此结束。

标签: ajax jquery


【解决方案1】:
  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/

【讨论】:

    【解决方案2】:

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

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

    来源ShoutingCode

    【讨论】:

      猜你喜欢
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多