Rails / Jquery Ajax - SyntaxError:意外的标识符,但JSON是有效的

时间:2017-01-11 19:13:35

标签: jquery ruby-on-rails json ajax coffeescript

我正在酒店聚合网站上工作,让用户调整过滤器(例如价格或客人数量),并通过ajax观看住宿刷新的可用性。它使用CoffeeScript和Jquery构建在Rails 4上。

这是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%的时间,服务器返回200状态(好),但Jquery失败,控制台显示以下内容:

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

此问题的每个其他stackoverflow问题看起来都是无效的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有效。如何进一步调试和解决此问题?

1 个答案:

答案 0 :(得分:2)

让我们从一个简化的例子开始,看看会发生什么。如果你在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<%= ... %>都不会引用/转义/编码'raw调用只是告诉ERB引擎不对其参数进行HTML编码,而您并未定位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>'

我非常倾向于重构事物,以便在JavaScript字符串中包含&#34; <script>&#34;不需要hackery。三层编码/转义有点多,非常容易出错。