ActionController::UnknownFormat with format.js for ajax implementation (Rail 4)

前端 未结 3 1532
难免孤独
难免孤独 2021-01-11 09:41

i try to use Ajax in my application with Rails 4. To send my js to the client i use :

   respond_to do |format|
        format.js 
   end

相关标签:
3条回答
  • 2021-01-11 09:49

    If you can use link_to helper function to call action of your controller, in your case Oweb::MainController#setmagasinstatus adding :remote => true to link_to helper will solve the issue.

    For example if you have a link to your action and want to get response in ajax the following code will create the link to that action:

    <%= link_to your_link_name, setmagasinstatus_path(:params), :remote => true %>

    Here is a dead easy sample https://coderwall.com/p/kqb3xq/rails-4-how-to-partials-ajax-dead-easy

    0 讨论(0)
  • 2021-01-11 09:53

    Catch:

    Your console log says:

    Processing by Oweb::MainController#setmagasinstatus as HTML

    In your controller action, you don't have supported HTML response. That's why you are facing error of UnknownFormat.

    Solution:

    Add format: "js" in your ajax call. For example:

    $.ajax url: "/oweb/main/setmagasinstatus", data: 'id=' + id, format: 'js'
    
    0 讨论(0)
  • 2021-01-11 10:13

    HTML

    Looks like the problem is you're sending an HTML request for whatever reason:

    Oweb::MainController#setmagasinstatus as HTML

    I'd surmise the "unkown format" error will therefore be caused by your lack of definition for the html mime-type in your action. I'd imagine this would work to resolve the error at surface-level:

     respond_to do |format|
         format.js 
         format.html
      end
    

    Ajax

    If the above is correct, the question then turns to "why is an HTML mime-type being sent?"

    Due to not being able to see your actual Ajax code, I'd recommend the problem will either be that you're just sending a standard HTTP request (ajax is XHR); or you'll have an issue with the declaration with the ajax request

    You must remember that Ajax (Asynchronous Javascript And XML) is meant to send a request on your behalf -- like a pseudo browser. This means if you want to send an ajax request, it has to be done through Javascript (hence the format.js mime type handler)

    --

    Personally, I think you're not sending an ajax request, although it could also be that you're sending a different dataType, such as JSON

    0 讨论(0)
提交回复
热议问题