繁体   English   中英

Rails呈现无效的json

[英]rails renders invalid json

我有一个奇怪的行为,一个ajax查询无法解析由我的rails 4.1.4服务器(jquery-rails为3.1.1)返回的JSON对象。 然而,控制器却是愚蠢的:

class WelcomeController < ApplicationController    
  def create
    respond_to do |format|
      format.json{ render json: 'ok' }
    end
  end   
end

而且Ajax查询都是非常标准的(CoffeeScript):

window.Api = {}

(->
  queryFx = (dataType, type, url, data, successFx, failureFx) ->
    $.ajax
      url: url
      type: type
      dataType: dataType
      beforeSend: (xhr) ->
        xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
      success: (json) ->
        console.log(json)
      error: (xhr, status, errorThrown) ->
        console.log(status, errorThrown)

  Api.post = (url) ->
    queryFx('json', 'POST', url)

)()

$(document).ready( ->
  $('#request').submit( (event) ->
    event.preventDefault
    window.Api.post($(this).attr('action'))
    return false #Prevent the normal submission
  )
)

查询进行得很好,只有当答复到来时,ajax才会抛出:

"parsererror" SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Stack trace:
jQuery.parseJSON@http://localhost:3000/assets/jquery.js?body=1:8483:3
ajaxConvert@http://localhost:3000/assets/jquery.js?body=1:8809:8
done@http://localhost:3000/assets/jquery.js?body=1:9226:4
.send/callback@http://localhost:3000/assets/jquery.js?body=1:9686:8

在rails服务器上有什么事情要做,因此它会为jquery输出正确的JSON?

您的控制器非常愚蠢,但是实际上确实渲染了无效的json;)您应该将Hash传递给render的json选项。 像这样尝试:

class WelcomeController < ApplicationController    
  def create
    respond_to do |format|
      format.json{ render json: { ok: 'ok' } }
    end
  end   
end

我刚刚面对过类似的问题。 我还建议您在将其用作json对象之前,先检查ajax响应字符串的无效格式。 我不熟悉coffeescript,这就是为什么我给您一个本机js示例。 因此,请尝试将以下代码放入AJAX完整的回调函数中:

    complete: function(data) {
        var jsonRes = null;
        try {
            jsonRes = JSON.parse(data.responseText);
        }
        catch(e) {
            jAlert('Invalid JSON object);
        }
        if (jsonRes===null || jsonRes.result===undefined) {
            jAlert('Invalid Ajax response structure');
        }
    }

暂无
暂无

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

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