【问题标题】:JSON object from rails not being parsed in .js.erb来自 rails 的 JSON 对象未在 .js.erb 中解析
【发布时间】:2019-01-20 18:23:42
【问题描述】:

我的控制器中有以下哈希:

@suggested_places = {
      "0": "Barcelona",
      "1": "Madrid",
      "2": "Valencia"
    }

我把它转成json:

@suggested_places_json = @suggested_places.to_json

这是输出:

=> "{\"0\":\"Barcelona\",\"1\":\"Madrid\",\"2\":\"Valencia\"}"

在我的 file.js.erb 中,我想使用这些信息。我想将 json 解析为 JavaScript 对象。我愿意:

const json = "<%= @suggested_places_json %>";
console.log(json);

结果如下:

{&quot;0&quot;:&quot;Barcelona&quot;,&quot;1&quot;:&quot;Madrid&quot;,&quot;2&quot;:&quot;Valencia&quot;}

为什么我有丑陋的 &quot 而不是我在后端拥有的 json? json 是一个字符串,它应该保持它的形式。

如果我尝试解析它:

console.log(JSON.parse(json));

我有以下结果:

Uncaught SyntaxError: Unexpected token & in JSON at position 1
    at JSON.parse (<anonymous>)
    at <anonymous>:6:18
    at processResponse (application-50000f29e1bf2752ae7e56dda39f10dd0f67a47aea5c3f07ed0d933f3e1a256a.js:268)
    at application-50000f29e1bf2752ae7e56dda39f10dd0f67a47aea5c3f07ed0d933f3e1a256a.js:196
    at XMLHttpRequest.xhr.onreadystatechange (application-50000f29e1bf2752ae7e56dda39f10dd0f67a47aea5c3f07ed0d933f3e1a256a.js:251)

有人可以帮我找出我在哪里做错了吗?我错过了什么?

【问题讨论】:

    标签: javascript ruby-on-rails json erb


    【解决方案1】:

    首先,您无法解析 json 输出,因为您已经放入了 @suggested_places.to_json 这样就足以获取数据,第二件事是生成 &quot 的原因是 (") 放入 json,所以如果您想要删除这个&quot你应该解码输出或者从输出中分解像\"这样的字符,但是最好的方法是第一个解码输出

    【讨论】:

    • 如果我执行:“Barcelona”,我对 &quot. 也有同样的问题。我不明白你的解决方案。你在暗示什么?你能说得更准确点吗?
    • 你不需要输出结果作为字段,但你需要第二个答案
    【解决方案2】:

    将数据从控制器传递到视图的两种方式:

    选项 1:

    您从视图向控制器发送了一个 json 请求:

    = link_to "load public places", load_public_places_path(format: :json), class: "btn btn-primary", remote: true, id: "loadPublicPlacesBtn"
    

    在您的控制器中,您以 json 格式响应,以及您想要返回的数据:

    def load_public_places
        latitude = params[:lat]
        longitude = params[:lng]
        @suggested_places = NearBySearchApiService.call(latitude, longitude)
    
        respond_to do |format|
          format.json { render json: @suggested_places.to_json }
          format.js
        end
    

    在要显示数据的视图中,监听ajax请求:

    :javascript
      document.getElementById('loadPublicPlacesBtn').addEventListener('ajax:success', function(event) {
        console.log(event);
      })
    

    选项 2:

    在视图中,你向控制器发送一个 JS 请求:

      = link_to "load public places with js", load_public_places_path, class: "btn btn-primary", remote: true, id: "loadPublicPlacesBtn"
    

    在控制器中,您回答 js 请求,该请求将在 load_public_places.js.erb 中

    def load_public_places
        latitude = params[:lat]
        longitude = params[:lng]
        @suggested_places = NearBySearchApiService.call(latitude, longitude)
    
        respond_to do |format|
          # format.json { render json: @suggested_places.to_json }
          format.js
        end
    

    这一次,由于您在视图中使用 erb,因此您可以使用实例变量 @suggested_places 而无需调用 to_json。

    在视图中,选择所需的 div,然后附加 HTML 内容(可以将其存储在部分中)

    const divWrapper = document.getElementById("optionCardsWrapper");
    
    divWrapper.innerHTML = "<%= j render "option_cards", suggested_places: @suggested_places %>";
    

    @suggested_places 是纯 ruby​​,你不需要解析它。

    j 是一个辅助方法,escape_javascript。

    在局部视图中,您可以将信息用作普通的 ruby​​ 对象

    %h1 option cards
    
    - suggested_places.each do |place|
      = place[:name]
    

    【讨论】:

      【解决方案3】:

      在互联网上搜索我找到了几年前的这个解决方案,我在一个带有 rails 6 的应用程序中对其进行了测试,并且效果很好。

      var contentLibrary = '<%= @content_library.to_json.html_safe %>'
      
      console.log(contentLibrary) // {"id":1,"title":"Welcome","status":"active"
      
      console.log(JSON.parse(contentLibrary)) // { id: 1, title: "Welcome", status: "active" }
      

      Embedding JSON in a Rails 4 JS/ERB template

      【讨论】:

        猜你喜欢
        • 2021-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-12
        • 2021-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多