0

我目前正在尝试通过 jRails 在我的应用程序中使用 AJAX。我试图从我的控制器返回一个 JSON 对象,然后在我的 Javascript 中解析它。我正在使用 json2.js 进行解析。

这是我目前拥有的代码:

function getSomething()
{
    $.ajax({
        type: "GET",
        url: "map/testjson",
        success: function(data) {
            var myData = JSON.parse(data[0]);
            window.alert(myData.login);
        }
    });
}

在控制器中:

class Map::MapController < ApplicationController
  def index
  end

  def testjson
    @message = User.find(:all)
    ActiveRecord::Base.include_root_in_json = false
    respond_to do |w|
      w.json { render :json => @message.to_json }
    end

  end
end

window.alert 只是说“未定义”(没有抽动)。

但是,如果我将 javascript 更改为 window.alert(data) (控制器返回的原始对象),我会得到:

[{"salt":"aSalt","name":"", "created_at":"2010-03-15T02:34:25Z","re​​member_token_expires_at": null,"crypted_pa​​ssword":"aPassword", "updated_at" :"2010-03-15T02:34:25Z","id":1,"remember_token":null, "login":"zgwrig2","email":"zach@zach.com"}]

如果我没看错的话,这看起来像一个大小为 1 的数组,但我已经尝试了我能想到的数据对象上 JSON.parse 的几乎所有组合,但似乎没有任何效果。

关于我在这里做错了什么的任何想法?

编辑 如果用户表中有不止一行,这似乎工作正常。

4

2 回答 2

0

我可以看到您的代码中有 2 个问题。

It is better if you use $.getJSON to do a JSON request.

  1. jQuery is yet a parser of JSON... then in your callback function you only must do:

$(data).each(function(i, user){ // what you like do with a user });

  1. In your rails response there a error, is not a w.json { render :json => @message.to_json }, is only w.json { render :json => @message }. Whiout ".to_json".

Hope that helps.

于 2010-03-16T08:32:10.263 回答
0

When there are more than one row, what you are deal is a String of your object in json format, not your json object representation. Really sorry for me english, i want explaind better ...

And if @message is a null object, because there isnt any messange, the render to json dont make anything, and when you are in your JS, you will have a problem because you dont have any response which worker. You must check your @message object. Maybe you can do that:

w.json {render :json => (@message.nil?) ? 0 : @checkpoint }

then, in your callback function you must check if your data response is "0" (like string) or one object.

于 2010-03-22T10:54:45.353 回答