2012-01-17 7 views
1

Iはモデルのクエリの結果をフェッチしました。次に、すぐに.to_jsonを追加し、正しいJSONオブジェクトを取得すると仮定しました。しかし、JQueryはjsonを解析できませんでした。Railsモデルで(コレクションの).to_jsonで作成されたJSONは読めないjquery

def self.get_all_specials(year) 
    data_array=AttributeCalendarAnnual.find(:all, :conditions=>["created_at between ? and ?",Date.civil(Date.today.year), Date.civil(Date.today.next_year.year)], :order=>["created_at asc"]) 
    return data_array.to_json 
end 

しかし、私が得た結果は、有効なJSONではありません。

EDIT 出力:

[{"created_at":"2012-01-17T17:38:27Z","id":1,"in_market_end_date":"2012-01-31T23:59:59Z","in_market_start_date":"2012-01-18T00:00:00Z","initiative_id":1,"is_mail_count_selected":true,"is_mailer_selected":true,"is_market_selected":true,"is_offer_selected":true,"mail_count":1,"mailer_start_date":"2012-01-25T00:00:00Z","offer_selection_end_date":"2012-01-12T23:59:59Z","offer_selection_start_date":"2012-01-09T00:00:00Z","updated_at":"2012-01-17T17:38:27Z"},{"created_at":"2012-01-17T20:21:37Z","id":2,"in_market_end_date":"2012-01-28T23:59:59Z","in_market_start_date":"2012-01-24T00:00:00Z","initiative_id":3,"is_mail_count_selected":true,"is_mailer_selected":true,"is_market_selected":true,"is_offer_selected":true,"mail_count":5,"mailer_start_date":"2012-01-30T00:00:00Z","offer_selection_end_date":"2012-01-21T23:59:59Z","offer_selection_start_date":"2012-01-09T00:00:00Z","updated_at":"2012-01-17T20:21:37Z"}] 
+0

その 'to_json'呼び出しから返されるものを投稿できますか? –

+0

出力を含む質問を編集しました – phoenixwizard

+2

これは有効なJSONではないと思われますか?あなたがビューでそれを使用している方法に問題があるかもしれませんが(私が理解するようにb jQueryを後で使用します)、JSON自体は正常に見えます。 –

答えて

1

単にあなたのページに脱出したオブジェクトを出力し、JSはそれが文字列として解釈されますので、これは動作しませんそれを解析します期待している場合。代わりに文字列を次のような関数に渡してみてください:

function parseJSON(txt, escape) { 
    if (escape === true) { 
     txt = unescape(txt); 
    } 
    return new Function("return " + txt)(); 
} 

var result = parseJSON(someString); 
関連する問題