开发者

rails 3 jquery button_to remote json not decoding

I'm using jQuery in a rails 3.1 project. I use a button_to with :remote => true :

<%= button_to "View Examples", "#{requisition_assign_path(@req.id, category_row.id)}?show_examples=1", :remote => true, :method => 'get' %>

This gets to the server fine, and is handled here :

   def show
    @assignment = Assignment.find params[:id]
    @tag = @assignment.assignee
    examples = []
    @tag.example[@tag.tag].each do |e|
      examples << {:id => e.id}
    end
    @examples_json = examples.to_json
    respond_to do |format|
    开发者_开发技巧  format.js {render "assign/show.js.erb"}
    end
  end

Which calls show.js.erb just fine :

alert(jQuery.parseJSON("<%= @examples_json %>");

But in the browser, the text arrives, but I can't get it to parse to the original array of hashes. What am I missing?

---- what I may have been missing is simply using jQuery's getJSON function...


Could you post the log for this action? One problem I did have with using the built in 'remote' helpers is that they request content in JS, not JSON. With your current controller code you will not get any response from $.getJSON (your controller is set to respond only to JS). You might try to add a respond_to block at the top of the controller

respond_to :html, :json

and your action might look like

def show
  @assignment = Assignment.find(params[:id])
  @tag = assignment.assignee
  @examples = []
  @tag.example[@tag.tag].each do |e|
    @examples << {:id => e.id}
  end
  respond_with(@examples)
end

What happens is that if you ask for JSON content the Rails 3 default Responder will automatically convert @examples to JSON. You might try this with the generic jQuery AJAX function

jQuery.ajax({
  url: $(this).attr('href'),
  type: 'GET',
  dataType: 'JSON',
  success: function(data){
    json = jQuery.parseJSON(data.responseText);
    console.log(json);
  }
});

Best regards!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜