简体   繁体   中英

Rails Action rendering html instead of json

I am using Rails 3. I really have a strange problem. I have a list of Country States as a select box, and I have hooked up jquery's $.ajax({}) , on change of the States select box.

The action takes a state code as a parameter and returns the districts that belong to a specific state. When the request is sent to /districts?state=1 , it responds with a status code of 302(found) and then it also sends the current html page as a response.

Following is my code:

# Controller Action

def districts
  state = params[:state]

  respond_to do |format|
    format.json{ render :json => get_districts(state) }
  end
end


# jQUery Request:

$.ajax({
    url: '<%= districts_path %>',
    data: {state: 1},
    success: function(data){
        for(i in data){
            options += '<option value="'+data[i].code+'">'+data[i].district+'</option>'
        }

        $("#some_element").html('<select id="some_district" name="some_district">'+options+'</select>')
    }
});

Try setting the dataType option to the ajax call:

$.ajax({
    url: '<%= districts_path %>',
    dataType: 'json',
    data: {state: 1},

edit added comma

HTTP 302, in my experience, is due to authentication issues. You should consider posting your controller code/routes and any authentication as well as any errors that may be occurring.

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