【问题标题】:Rendering partial with ajax and json response使用 ajax 和 json 响应渲染部分
【发布时间】:2013-05-07 17:27:44
【问题描述】:

我正在尝试渲染一个调用 ajax 函数的部分并在 div 中渲染它。

在下面的代码中,request.responseText 给了我想要的 html,但是为什么这个响应会进入错误函数而不是成功? 这似乎很简单,但我在这里遗漏了一些东西。 chrome 的检查元素中的后响应状态代码为“200 OK”

js代码:

$.ajax({
        url: "/upload/get_detail.json",
            type: "POST",
            dataType: "json",
            data: { id: id },
            success: function(result) {
                $('.some-label').html(result);
            },
            error: function (request, status, error) {
                alert(request.responseText);
            }
        }).done(function() {
           //some code
        });

控制器:

  def get_detail
    @logs = Detail.where('category_id = ?', params[:id].to_i).limit(20)
    render :partial => "/category/detail", :layout=> false
  end

【问题讨论】:

  • responseText 是什么样的?
  • 您的 "html" 很可能不是 json。
  • 这是一个 HTML。实际上,这是个好问题,因为我忘了包括重要部分,错误:Unexpected token <
  • 正确。您的 dataType 设置为 JSON,但您正在返回 HTML。因此 jQuery 将请求视为失败,因为 JSON !== HTML。如果要返回 html,请将 dataType 设置为“html”或一起删除 dataType。
  • 那是对的。谢谢

标签: jquery ruby-on-rails ajax


【解决方案1】:

您正在从服务器发送 HTML,但您已将 jQuery.ajax 调用配置为期待 JSON。将dataType 属性更改为html,它应该可以工作。

【讨论】:

    猜你喜欢
    • 2011-09-14
    • 2013-01-29
    • 2017-04-09
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    相关资源
    最近更新 更多