我按照教程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)
答案 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.rb
将create
方法更改为:
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
端
我希望这能解决你的问题。