AJAX成功函数未被调用

use*_*030 8 javascript ajax jquery ruby-on-rails

我试图从AJAX调用获取成功函数到fire.我知道它正常工作,因为我正在使用自己的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");
  }
});
Run Code Online (Sandbox Code Playgroud)

api方法

class UsersController < ApplicationController
    respond_to :json

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

end
Run Code Online (Sandbox Code Playgroud)

服务器日志

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
Run Code Online (Sandbox Code Playgroud)

Ash*_*mar 20

这也发生在我身上很长一段时间,我通过将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 = eval(response);
    return alert("Hey");
  }
});
Run Code Online (Sandbox Code Playgroud)

愿这对你有用.

  • 使用JSON.parse(响应); 代替. (9认同)

Sem*_*Zen 5

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

complete: function(response, textStatus) {
    return alert("Hey: " + textStatus);
  }
Run Code Online (Sandbox Code Playgroud)