如何使用ResponseText

时间:2014-07-01 22:05:22

标签: javascript jquery json

前言:请原谅我,因为在处理JSON时我是一个很新的人。

我目前正在使用Rails和jQuery通过JSON检索一些数据。我能够成功地从我的控制器中获取数据,但我似乎无法用它做任何事情。

index.html.erb

<a href="#" id="click">Click Me</a>

clothing.js.erb

$( "#click" ).on( "click", function(e) {
   e.preventDefault();
   $.ajax({
    type: "GET",
    dataType: "json",
    url: "/clothing/get_color",
    success: function(response){
        alert(response);
    }
   })
});

clothing_controller.rb

 def get_color
    #Query goes here

    respond_to do |format|
        format.html
        format.json { render :json => @color, status: :ok }
    end
 end

当我点击$("#click")链接,查看我的Firebug控制台时,它成功查询控制器,没有任何错误,并将response显示为blue

但是,我对此回复无法采取任何措施,例如alert(response)$("#my_input").val(response)

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

2 个答案:

答案 0 :(得分:0)

在尝试输出响应之前,您可能需要执行响应的JSON.stringify()。

点击此链接https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

答案 1 :(得分:0)

好的,我明白了。事实证明它在JSON请求之后触发了“错误”,而不是成功,即使它的状态为200也是如此。

所以,我发现了这个帖子here,解释了添加:success=> "success"。所以,我将控制器代码更改为:

respond_to do |format|
 format.json { render :json => { :success => "success", :status_code => "200", :color => @color } }
end

这很有效!