【问题标题】:AJAX success function not being called未调用 AJAX 成功函数
【发布时间】:2013-08-04 10:35:22
【问题描述】:

我正在尝试从触发 AJAX 调用中获取成功函数。我知道它工作正常,因为我正在访问我自己的 API,我可以看到它正在正确访问 URL,并且服务器正在输出 HTTP 200。

我认为这是因为服务器正在输出 json,所以我尝试在 AJAX 调用中考虑这一点,但仍然无法成功功能。这是我的代码

ajax

$.ajax('http://localhost:3000/api/users/show/:id', {
  type: 'GET',
  dataType: 'json',
  contentType: "application/json",
  data: {
    id: 1
  },
  success: function(response) {
    return alert("Hey");
  }
});

api方法

class UsersController < ApplicationController
    respond_to :json

    def show
        respond_with User.find(params[:id])
    end

end

服务器日志

Started GET "/api/users/show/:id?id=1" for 127.0.0.1 at 2013-08-02 20:36:42 -0700
Processing by MainController#index as JSON
  Parameters: {"id"=>"1", "path"=>"api/users/show/:id", "main"=>{}}
  User Load (0.5ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
  Rendered main/index.html.erb within layouts/application (0.6ms)
Completed 200 OK in 146ms (Views: 144.3ms | ActiveRecord: 0.5ms)
[2013-08-02 20:36:42] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

【问题讨论】:

标签: javascript jquery ruby-on-rails ajax


【解决方案1】:

这也发生在我很久以前,我通过将 dataType 更改为文本并通过 eval 手动将其转换为 json 对象来解决这个问题。

$.ajax('http://localhost:3000/api/users/show/:id', {
  type: 'GET',
  dataType: 'text',
  contentType: "application/json",
  data: {
    id: 1
  },
  success: function(response) {
    response = JSON.parse(response);
    return alert("Hey");
  }
});

愿这对你有用。

【讨论】:

  • 使用 JSON.parse(response);而是。
  • 由于 XSS 风险,你永远不应该使用 eval 函数
【解决方案2】:

我会添加一个完整的函数并检查文本状态。这应该提供解决问题所需的信息。

complete: function(response, textStatus) {
    return alert("Hey: " + textStatus);
  }

【讨论】:

    【解决方案3】:

    我认为问题是我一直在经历的,我想我有答案。看起来您的调用正在检索 HTML 视图,正如我从“在布局/应用程序中渲染的 main/index.html.erb”中推断的那样,尽管我不熟悉您正在使用的任何 API 堆栈。

    我在 ASP.NET MVC 5 上的症状是调用了完成,但没有调用任何错误、成功或超时。在响应对象上,状态为 200,statusText 为“OK”,但 textStatus 参数为“parsererror”。

    responseText 是我期待的 html,但我忘记了我已经从检索 json 转移到 html,所以在将 datatype: 'json' 更改为 datatype: 'html' 后,它现在可以工作了。

    【讨论】:

      【解决方案4】:

      考虑到这个类,它显然没有调用您期望的方法:

       class UsersController < ApplicationController
      

      我们应该在您的日志中看到类似的内容:

      Processing by UsersController#show as JSON
      

      但您的日志显示如下:

      Processing by MainController#index as JSON
      

      我的猜测是你的路线是错误的。检查路线以及为什么它没有调用UsersController#show 方法。还要确定的是,使用浏览器(chrome、firefox),您应该能够检查请求的响应以确保它实际上正在接收 json 或 html。

      因为它试图渲染main.html.erb。我对dataType: "json" 不起作用并不感到惊讶。但是,如果您实际上返回的是有效的 json,它应该可以工作。但是您的 Rails 日志显示您可能正在返回 html。

      【讨论】:

        【解决方案5】:

        我遇到了同样的问题,我通过在关闭成功函数后添加一个冒号解决了它。

        【讨论】:

          猜你喜欢
          • 2023-03-08
          • 2013-02-14
          • 1970-01-01
          • 2012-07-27
          • 1970-01-01
          • 1970-01-01
          • 2015-01-15
          • 2017-01-21
          • 1970-01-01
          相关资源
          最近更新 更多