jquery - Rails/Jquery Ajax - SyntaxError : Unexpected identifier, 但 JSON 有效

标签 jquery ruby-on-rails json ajax coffeescript

我正在开发一个酒店聚合网站,该网站允许用户调整过滤器(例如价格或客人数量)并通过 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% 的情况下,服务器返回 200 状态(好的),但 Jquery 失败,控制台显示以下内容:

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

与此问题相关的所有其他 stackoverflow 问题看起来都像是传递回 Jquery 的 JSON 无效。我在 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也不<%= ... %>将引用/转义/编码 ' 。那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>'

我强烈倾向于重构,这样就不需要“<script> inside a JavaScript string”黑客行为了。三层编码/转义有点多,而且很容易出错。

关于jquery - Rails/Jquery Ajax - SyntaxError : Unexpected identifier, 但 JSON 有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41598931/

相关文章:

javascript - Codeigniter:接受空格和符号以使用 JQuery 进行验证

javascript - e.target 是上下文菜单可见时点击的主体

ruby-on-rails - 如何使我的网站由于图像而变快变慢

ruby-on-rails - 如何正确扩展 Devise Recoverable?

json - Swift Google Directions API JSON - EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)

java - 当只有一个对象时将XML转换为Json数组Java

javascript - jsplumb 如何使用直连器

ruby-on-rails - has_many 和单表继承

java - 使用java创建一个json对象并将其存储在mysql中

jquery - 检查复选框是否在点击时未被选中 - jQuery