Jquery 如何使用rails引导模式通过ajax提交表单
我按照教程将ajax表单添加到我的rails应用程序中。 一切正常,除了我没有收到无效表单上的错误消息。当我检查谷歌chrome控制台时,我发现Jquery 如何使用rails引导模式通过ajax提交表单,jquery,ruby-on-rails,ajax,twitter-bootstrap,error-handling,Jquery,Ruby On Rails,Ajax,Twitter Bootstrap,Error Handling,我按照教程将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.on
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)
我认为这与来自服务器的意外响应格式有关,因为您使用format.js呈现json 我建议您将处理错误的脚本移动到名为
app/views/people/create_errors.js.erb
的文件中,并在其中添加以下行,而不是在app/assets/javascripts/people.js
$('form#new_person').render_form_errors(<%= @person.errors.to_json.html_safe %>);
结束
我希望这能解决您的问题。我尝试删除js文件,但仍然出现相同的错误。错误消息表明,当服务器回复ajax请求时,问题与processResponse有关。您能打印console.log输出吗?它不会在控制台日志中打印任何内容。就像它在错误处停止,文件中的代码被跳过。如何在服务器端发送错误
render json:@person.errors,status::unprocessable_entity
与此完全相同,或者您进行更改???format.html{render:new}
format.json{render json:@person.errors,status::unprocessable_entity}
format.js render json:@person.errors,status::unprocessable_entity}
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