简体   繁体   中英

POST 500 (Internal Server Error) using Ajax, React and Rails

I'm just taking a step to use Ajax so I may missed something very important. Instead of having the page to refresh, I now want to use ajax. I'm testing a small code but the browser console says:

POST 500 (Internal Server Error)

Routes:

post 'to/test' => 'foo#bar'

.jsx:

test(e){
    $.ajax({
      url: 'to/test',
      type: 'POST',
    });
},

foo_controller.rb:

def bar
 u = User.last
 u.age = 99
 u.save
end

Looking at my rails console, the user's age was set to 99. Anything I've missed in my ajax learning?

Change this:

url: 'to/test'

To this:

url: '/to/test'

Otherwise the ajax call will use the path local to the current path, not the path local to the domain.

Edit: scrap that, a 500 error probably means something else. What do your server logs say? You may need to ensure that the action method responds to js with a respond_to block, and have a bar.js.erb template file to go with it.

I am pretty sure I know the answer, it's a Template is missing error, just add head :ok :

def bar
  u = User.last
  u.age = 99
  u.save
  head :ok
end

head(status, options = {})

Returns a response that has no content (merely headers). The options argument is interpreted to be a hash of header names and values. This allows you to easily return a response that consists only of significant headers.

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