簡體   English   中英

在Rails中渲染后如何在javascript中訪問json

[英]How to access json in javascript after rendering it in rails

如果我在Ruby中呈現json,如何訪問javascript中的值?

在紅寶石中,如果我寫:

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

如何在javascript中訪問“ val”?

如果我在javascript中執行alert(response),我會在json周圍看到一個標簽,這會有所不同還是期望?

我嘗試了jQuery.parseJSON(response),但是出現語法錯誤。 如果我嘗試直接訪問響應,則無法獲得正確的值-應該

response.key === "val"

評估為真?

我是在Ruby中設置錯誤還是在javascript中訪問錯誤?

如果您可以顯示JavaScript代碼,那將真的有幫助。
無論如何,一種實現方法是使用jQuery的ajax函數並將dataType設置為json。

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

希望這可以幫助。

這是一個簡單的例子。

在./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" %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM