13

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

我认为这是因为服务器正在输出 json,所以我尝试在 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
4

5 回答 5

22

这也发生在我很久以前,我通过将 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");
  }
});

愿这对你有用。

于 2013-08-03T04:09:19.167 回答
8

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

complete: function(response, textStatus) {
    return alert("Hey: " + textStatus);
  }
于 2013-08-03T03:59:27.083 回答
2

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

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

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

于 2014-03-03T01:06:51.080 回答
0

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

 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。

于 2014-03-03T01:14:47.327 回答
0

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

于 2021-06-14T00:20:57.440 回答