Rails将状态代码返回给Ajax,返回undefined

时间:2017-02-16 21:54:06

标签: jquery ruby-on-rails ajax

我确信我在这里错过了一些非常简单的事情......

JQUERY CODE

  $.ajax({
    type : "POST",
    url :  '/orders/create_or_update',
    dataType: 'json', 
    contentType: 'application/json',
    data : JSON.stringify(params)
  })
  .done(function(response){
    console.log(response.status)
    console.log(response)
  })

CONTROLLER CODE

  def create_or_update
    ...
    render json: {"name" => "test"}, status: 200
  end

OUTPUT OF CONSOLE.LOG

  undefined
  Object: {name: "test"}

为什么我的jQuery中的response.status没有返回status: 200

1 个答案:

答案 0 :(得分:0)

<强> EDIT2:

实际上,对于.always函数,如果响应成功,则参数为(data, textStatus, jqXHR),但如果失败,则为(jqXHR, textStatus, errorThrown)

在文档中,它是这样说的:

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { })

jQuery Docs

因此,您需要if/else在所有回复中始终显示jqXHR.status

修改

您的response只是您从render来电回来的对象。它没有任何地位概念。这就是为什么当你.status时它未定义。我认为.always是必要的b / c它将涵盖来自控制器的.done.fail响应。如果你只是要获得.done方法,并且你希望它能够处理它,你可以这样做(注意额外的textStatus参数):

  $.ajax({
    type : "POST",
    url :  '/orders/create_or_update',
    dataType: 'json', 
    contentType: 'application/json',
    data : JSON.stringify(params)
  })
  .done(function(response, textStatus, xhr){
    console.log(xhr.status)
    console.log(response)
  })

所以,你应该能够做到这一点:

  $.ajax({
    type : "POST",
    url :  '/orders/create_or_update',
    dataType: 'json', 
    contentType: 'application/json',
    data : JSON.stringify(params)
  })
  .done(function(response){
    console.log(response.status)
    console.log(response)
  }).always(function(a, textStatus, b){
    console.log(a.status); // One of these two will be `undefined`
    console.log(b.status);
  })

这会将状态打印到日志中。