如何使用rails bootstrap模式通过ajax提交表单

时间:2017-07-16 09:02:34

标签: jquery ruby-on-rails ajax twitter-bootstrap error-handling

我按照教程here将ajax表单添加到我的rails应用程序中。 一切正常,除非我在无效表单上收到错误消息。当我检查谷歌Chrome控制台时,我得到了

Uncaught SyntaxError: Unexpected token :   
   at processResponse (rails-ujs.self-661556f….js?body=1:246)
   at rails-ujs.self-661556f….js?body=1:173
   at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.self-661556f….js?body=1:230)

Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)

Uncaught SyntaxError: Unexpected token :
   at processResponse (rails-ujs.self-661556f….js?body=1:246)
   at rails-ujs.self-661556f….js?body=1:173
   at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.self-661556f….js?body=1:230) 

POST http://localhost:3000/people 422 (Unprocessable Entity) 

1 个答案:

答案 0 :(得分:0)

我认为它与服务器的意外响应格式有关,因为您使用format.js

呈现json

我建议您将处理错误的脚本移动到名为app/views/people/create_errors.js.erb的文件中,并在其中添加以下行,而不是在app/assets/javascripts/people.js中绑定ajaxError事件

$('form#new_person').render_form_errors(<%= @person.errors.to_json.html_safe %>);

app/controllers/people_controller.rbcreate方法更改为:

def create
@person = Person.new(person_params)

respond_to do |format|
  if @person.save
    format.html { redirect_to @person, notice: 'Person was successfully created.' }
    format.json { render action: 'show', status: :created, location: @person }
    # added:
    format.js   { render action: 'show', status: :created, location: @person }
  else
    format.html { render action: 'new' }
    format.json { render json: @person.errors, status: :unprocessable_entity }
    # added:
    format.js   { render 'create_errors', status: :unprocessable_entity }
  end
end

我希望这能解决你的问题。