rails 4:对ajax post的响应导致呈现响应的错误

时间:2022-08-06 20:14:48

In my rails 4 project, I submit data with a POST and jquery like this (watch out, coffee-script):

在我的rails 4项目中,我使用POST和jquery这样提交数据(注意,咖啡脚本):

post_data =
        site_id: site
        url: '//' + $('#host-holder').data('host') + '/' + key

$.post("/sites/" + site + "/images",post_data, (success) ->
        #successful_post
 ).fail( (xhr, textStatus, errorThrown) ->
        #post failed
 )

In my controller, if I do:

在我的控制器中,如果我这样做:

respond_to do |format|
      format.js {render nothing: true}
end

the POST submit works fine (success callback in ajax client runs), but if I do this:

POST提交工作正常(在ajax客户端运行中成功回调),但如果我这样做:

respond_to do |format|
      format.js {render json: @image.to_json, status: :created}
end

it fails (fail callback in ajax client runs).

它失败(在ajax客户端运行中失败回调)。

Why that? What am I doing wrong in responding to the ajax request? (Note: no error reported server-side)

为什么?我在回应ajax请求时做错了什么? (注意:服务器端没有报告错误)

EDIT: The error is "parsererror", I actually have the whole object there! It says "missing ; before statement"...and this is the response object: "{"id":24,"url":"<EDITED FOR SECURITY>","thumbnail":null,"status":null,"site_id":28,"created_at":"2014-10-05T02:53:50.030Z","updated_at":"2014-10-05T02:53:50.030Z","quality":"good"}"

编辑:错误是“parsererror”,我实际上有整个对象!它说“缺少;在声明之前”......这是响应对象:“{”id“:24,”url“:” “,”thumbnail“:null,”status“:null, “SITE_ID”:28, “created_at”: “2014-10-05T02:53:50.030Z”, “的updated_at”: “2014-10-05T02:53:50.030Z”, “质量”: “好”}”

1 个解决方案

#1


0  

Here Your ajax statement should like this,

在这里你的ajax声明应该是这样的,

$.ajax({
  URL: '/controller_name/action_name',           // url must be proper
  type: 'POST',
  data: { username: 'test' },
  success: function(response){
    alert(response);
  },
})

In Route.rb:

post '/action_name' => 'controller_name#action_name'

In Controller file:

在Controller文件中:

def action_name
  @username = params[:username]
  data = {:message => "Alert this!"}
  render :json => data
end

#1


0  

Here Your ajax statement should like this,

在这里你的ajax声明应该是这样的,

$.ajax({
  URL: '/controller_name/action_name',           // url must be proper
  type: 'POST',
  data: { username: 'test' },
  success: function(response){
    alert(response);
  },
})

In Route.rb:

post '/action_name' => 'controller_name#action_name'

In Controller file:

在Controller文件中:

def action_name
  @username = params[:username]
  data = {:message => "Alert this!"}
  render :json => data
end