1

Ruby で json をレンダリングする場合、javascript で値にアクセスするにはどうすればよいですか?

ルビーで、私が書くと:

response = {:key => "val"}
response = response.to_json
render :json => response, :status => 200

javascriptで「val」にアクセスするにはどうすればよいですか?

javascript でアラート (応答) を実行すると、json を囲むタグが表示されます。これは違いがありますか?

jQuery.parseJSON(response) を試しましたが、構文エラーが発生しました。応答に直接アクセスしようとすると、正しい値が得られません。

response.key === "val"

true と評価されますか?

Ruby で正しく設定していないか、javascript で正しくアクセスしていないか、またはその両方ですか?

4

2 に答える 2

1

JavaScriptコードを表示できると本当に助かります。
とにかく、それを行う 1 つの方法は、jQuery の ajax 関数を使用し、dataType を json に設定することです。

$.ajax({
    type: "GET",
    url: "<your link>",
    dataType: "json",
    success: function(response) {
      if (response.key)
        alert(response.key);
    });
});

お役に立てれば。

于 2012-05-18T07:10:23.550 に答える
0

これが簡単な例です。

./config/routes.rb内

match '/index' => 'application#index'
match '/json' => 'application#json'

コントローラー、。/ app / controllers / application_controller.rb:

class ApplicationController < ActionController::Base
  protect_from_forgery

  def index
    # server side code required by index
  end

  def json
    response = {:key => "val"}
    response = response.to_json
    render :json => response, :status => 200
  end
end

ajaxリクエストが作成されたerbページ、この場合は./app/views/application/index.html.erb:

<script type="text/javascript" charset="utf-8">
    $(document).ready(
        function(){
            $("a#my_ajax").bind("ajax:success",
                function(evt, data, status, xhr){
                    console.log(data.key);
                    console.log(data.key === "val");
                }).bind("ajax:error", function(evt, data, status, xhr){
                    console.log("doh!")
                });
    });
</script>

<%= link_to "test",  {:controller=>"application",  :action => 'json'}, :remote=> true, :id => "my_ajax" %>
于 2012-05-18T07:15:14.740 に答える