简体   繁体   English

Rails Ajax错误-SyntaxError:JSON中位置0处的意外令牌C

[英]Rails ajax error - SyntaxError: Unexpected token C in JSON at position 0

In my view file I have the following jQuery AJAX call 在我的视图文件中,我有以下jQuery AJAX调用

<% if flash[:notice] %>
  <div class="notice"><%= flash[:notice] %></div>
<% end %>
.
.
.
function updateFunction() {
    var input = JSON.stringify({data: hot.getData()});

    $.ajax({
        type: 'POST',
        url: "/cars/create",
        data: input,
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: create_data_succ,
        error: create_data_error
    });
}

function create_data_error(XMLHttpRequest, textStatus, errorThrown) {
    alert(errorThrown);
}

In may cars_controller.rb I have cars_controller.rb我有

  def create
    Car.create(name: params[:data][:name])
    flash.now[:notice] = 'New Car!'
    render "new"
  end

Data is saving to db but I can't see the notice message on the screen, instead I am getting the alert message (error callback jQuery AJAX) 数据正在保存到db,但我在屏幕上看不到通知消息,而是收到警报消息(错误回调jQuery AJAX)

SyntaxError: Unexpected token C in JSON at position 0 SyntaxError:JSON中位置0处的意外令牌C

what am I doing wrong? 我究竟做错了什么? Any help much appreciated 任何帮助,不胜感激

The data is sent correctly to the controller, since the data saves to the DB; 由于数据已保存到数据库,因此数据已正确发送到控制器; the error lies with the response. 错误在于响应。 You're doing a render 'new' on a successful create, which sends HTML back as response to the AJAX call. 您正在成功创建一个render 'new' ,该render 'new'将HTML发送回作为对AJAX调用的响应。 Maybe something like: 也许像:

car = Car.new(name: params[:data][:name])
unless car.save
   render json: { errors: error }
end
...

If you need both html and json response (for whatever reason) you can do this via respond_to 如果您需要HTML和JSON响应(无论何种原因),您可以通过做到这一点respond_to

respond_to do |format|
   format.html  { render :new } 
   format.json  { render json: { ... } }
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM