【问题标题】:How to submit form via ajax using rails bootstrap modal如何使用rails bootstrap modal通过ajax提交表单
【发布时间】:2017-12-20 23:07:51
【问题描述】:

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

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) 

【问题讨论】:

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


    【解决方案1】:

    我认为这与来自服务器的意外响应格式有关,因为您使用 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
    

    结束

    希望这能解决您的问题。

    【讨论】:

    • 我尝试删除 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 }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-14
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 2018-12-04
    相关资源
    最近更新 更多