简体   繁体   中英

If you know how to get JSON working with Rails 3.2, can you figure this out?

I'm trying to build a dynamic menu so when the user selects a country, the state menu is updated.

I'm looking at my dev logs and I see that the action runs the db query and then renders the json.erb file, but I can't get any response from the browser.

Here's what I have:

controllers/settings_controller.rb

respond_to :html, :json

  def getstates
    @states = Country.find_by_iso(params[:account][:addresses_attributes]["0"][:country]).states
    respond_with(@states)
  end

(Note: The form is a nested form, that's why the params hash is so long.)


settings/edit.html.erb

<%= address.collection_select :country, Country.order(:name), :iso, :name, {:include_blank => true}, "data-remote" => true, "data-url" => "/settings/getstates", "data-type" => :json  %>

<%= address.select :state, [], {:include_blank => true}, :disable => true %>

settings/getstates.json.erb

$(document).ready(function() {

    $("#account_addresses_attributes_0_country").bind('ajax:success', function(evt, data, status, xhr){
      var select = $('#account_addresses_attributes_0_state');

      if (data !== null) {
        select.removeAttr('disabled');
        $.each(data, function(key, value) {
          $("<option/>").val(value[1]).text(value[0]).appendTo(select);
        });
      } else {
        select.empty();
        select.attr('disabled', 'disabled');
      }
    });
});

(Note: I got this code from http://blog.madebydna.com/all/code/2011/12/05/ajax-in-rails-3.html )


Dev logs

Processing by SettingsController#getstates as JSON
  Parameters: {"account"=>{"addresses_attributes"=>{"0"=>{"country"=>"UY"}}}}
  User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", "1"]]
  Country Load (0.2ms)  SELECT "countries".* FROM "countries" WHERE "countries"."iso" = 'UY' LIMIT 1
  Rendered settings/getstates.json.erb (0.3ms)
Completed 200 OK in 3ms (Views: 1.5ms | ActiveRecord: 0.3ms)

This is the output I see in my dev logs. But nothing in the browser. I've tried adding alerts and console log methods, but nothing.

I'd really appreciate if someone could help me understand what I'm doing wrong.

First, I'm a little confused about your .json.erb view. It looks like you're returning Javascript (to execute in the browser) when the REST request is asking for JSON.

Secondly, I'd take a look at your favorite Firebug alike tool (be that Chrome's Developer Tools or Safari's... whatever. Take a look at what's coming back from the AJAX request you're making to the server. (Maybe it's not what you expect - either an error code or you're getting something different from what you - or the collection_select expects).

My guess is that your .json view is spitting back actual Javascript, which then (something) tries to parse as JSON, fails and gives a Javascript error message somewhere (aborting the Javascript). Again, easiest way to track down one of those is with a Firebug-alike.

If you use Firebug's console tab, you'll see the ajax request be made. Then you can open it up and see the response body. Like Ryan has suggested you're requesting JSON but returning full javascript. So if you were to keep it that way you'd have to eval the response in your callback function ie eval(data) or jQuery also has a shortcut where you can request a 'script' type; But it's kinda frowned upon now that RJS has been removed from Rails. Instead do as Dan has suggested, move the contents of settings/getstates.json.erb into your edit view, and delete the getstates.json.erb file. To aid you in making this work make the request/response simplier for now. Just do this and inspect it in Firebug to see what's happening. After which, hook it up to turn the response contents into the option tags you're wanting.

$.get("/settings/getstates", function(data){
  console.log(data);
}, 'json')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM