Rails/Jquery Ajax - SyntaxError: Unexpected identifier, but JSON is Valid

Rails/Jquery Ajax - SyntaxError: Unexpected identifier, but JSON is Valid

我正在开发一个酒店聚合网站,该网站允许用户调整过滤器(例如价格或客人数量)并通过 ajax 刷新住宿可用性。它基于 Rails 4,使用 CoffeeScript 和 Jquery 构建。

这是 JQuery 调用 (Coffeescript):

$.ajax '/accommodations/show',
      type: 'GET'
      dataType : 'script'
      data:
        privates: include_privates
        shared: include_shared
        homes: include_homes
        price_range: price_range
        start_date: start_date
        end_date: end_date
        num_guests: num_guests
      success: (data) ->
        #RESPONSE DOES NOT HAPPEN HERE, IS HANDLED IN SHOW.JS.ERB
        console.log "Success!"
        console.log data
      error: (data, status, error) ->
        console.log 'How embarassing! Something went wrong - please try your search again. '
        console.log "Status: #{status}"
        console.log "Error: #{error}"

90% 的时间,这段代码都有效。其他 10% 的时间,服务器 returns 200 状态(好的),但 Jquery 失败并且控制台显示以下内容:

How embarassing! Something went wrong - please try your search again. 
Status: parsererror
Error: SyntaxError: Unexpected identifier

关于此问题的所有其他 Whosebug 问题看起来都是无效的 JSON 被传回 Jquery。我在 show.js.coffee.erb 中确定了问题行。这是我们将 rails 模型转换为 JSON 的地方,因此它可以传递给 javascript。

$('.refresh-loading').hide()
//Adding the accommodation modules to the left-hand side
$('#accommodation-modules-wrapper').html("<%= escape_javascript(render partial: 'accommodations/accomm_modules', locals: {properties: @accommodations, slider_min: @price_low, slider_max: @price_high})%>")
window.init_isotope()

//Removing the loading icon
$('.refresh-loading').hide()

//THIS IS WHERE THE ERROR IS
//Removing this line fixes the issue
marker_string = '<script>window.accommodation_markers = <%= raw @accommodations.to_json %>;</script>'

raw @accommodations.to_json 的输出如下:

[{
    "id": 741580,
    "name": "Gamer's Paradise in Brooklyn!",
    "google_place_id": "ChIJOwg_06VPwokRYv534QaPC8g",
    "type_code": "hotel",
    "external_id": 2243038,
    "lat": 40.694426,
    "lng": -73.94636,
    "location_rating": 9.0,
    "overall_rating": 9.0,
    "review_count": 13,
    "currency_code": "USD",
    "average_nightly_price": 30.0,
    "image_url": "https://a2.muscache.com/im/pictures/asdfa-4cf7-4222-9204-619200def457.jpg?aki_policy=small",
    "url": "https://www.test.com/rooms/13396285",
    "review_url": "https://www.test.com/rooms/13396285#reviews",
    "accommodation_cluster_id": null,
    "created_at": "2016-12-07T11:22:21.319-08:00",
    "updated_at": "2016-12-14T08:48:51.073-08:00",
    "usd_average_nightly_price": "30.0",
    "city_rank": 0,
    "city_rank_price": 15,
    "city_rank_reviews": 511,
    "cluster_rank": 0,
    "cluster_rank_price": 0,
    "cluster_rank_reviews": 1,
    "shared_room": true,
    "private_room": false,
    "entire_home": false,
    "external_uid": null
}]

根据 JSONLint,此输出有效。我该如何进一步调试和解决这个问题?

让我们从一个简化的例子开始,看看会发生什么。如果你在 Ruby 中有这个:

@thing = { :id => 741580, :name => "Gamer's Paradise in Brooklyn!" }

然后在某些 ERB 中你说:

thing = '<%=raw @thing.to_json %>'

然后你会看到这样的输出:

thing = '{"id":741580,"name":"Gamer's Paradise in Brooklyn!"}'

这就是你的问题:raw<%= ... %> 都不会 quote/escape/encode '。该 raw 调用只是告诉 ERB 引擎不要 HTML-encode 它的参数,并且您没有针对 HTML 因此您将 raw 功能混合在一起。但是你想要更多,你想要转义那些引号。

可能最简单的方法是使用 String#html_safeescape_javascript。但是你在 ERB 生成的 JavaScript 字符串中有 JavaScript 所以你需要双重转义;一些令人不快的事情,例如:

marker_string = '<script>window.accommodation_markers = <%= escape_javascript(escape_javascript(@accommodations.to_json.html_safe)) %>;</script>'

我强烈倾向于重构事物,这样就不需要“<script> inside a JavaScript string”黑客技术了。三层encoding/escaping有点多而且很容易出错