2016-01-22 65 views
1

我能用JSON响应escape_javascript?Rails的escape_javascript对JSON

我运行与Facebook的Rails 4.2.1和测试的OAuth。我使用Facebook SDK将link_to与远程true和ajax请求进行了关联。

window.fbAsyncInit = -> 
    FB.init 
     appId: 'AppID' 
     status: true 
     cookie: true 
     xfbml: true 
    return 

    ((d) -> 
    js = undefined 
    id = 'facebook-jssdk' 
    if d.getElementById(id) 
     return 
    js = d.createElement('script') 
    js.id = id 
    js.async = true 
    js.src = '//connect.facebook.net/en_US/all.js' 
    d.getElementsByTagName('head')[0].appendChild js 
    return 
) document 
    $ -> 
    $('#facebook, #vkontakte').click (e) -> 
     e.preventDefault() 
     FB.login ((response) -> 
     if response.authResponse 
      $('.modal').modal('hide') 
      # $('#results').html 'Connected! Hitting OmniAuth callback (GET users/auth/facebook/callback)...' 
      # since we have cookies enabled, this request will allow omniauth to parse 
      # out the auth code from the signed request in the fbsr_XXX cookie 

      $.getJSON '/profile/auth/facebook/callback', (json) -> 
      # $('#results').html JSON.stringify(json) 
      # Do some other stuff here (call more json, load in more elements, etc) 
      return 
     return 
    ), scope: 'email' 
     # These are the permissions you are requesting 
     return 
    $('#connect .signout').click (e) -> 
     e.preventDefault() 
     $.getJSON '/auth/facebook/signout', (json) -> 
     $('#results').html JSON.stringify(json) 
     return 
     return 
    return 

一切正常,我得到了我的用户用他的帐户登录,但我需要做一些前端更新(即重新渲染几个谐音等。)我不喜欢远程真实javascript_escape概念所以我很乐意使用JSON的相同,但找不到任何的例子..

回答

0

终于想出了另一种思路,提出招AJAX JS的变化不大。

$('#facebook, #vkontakte').click (e) -> 
    e.preventDefault() 
    FB.login ((response) -> 
    $('.modal').modal('hide') 
    # $('#results').html 'Connected! Hitting OmniAuth callback (GET users/auth/facebook/callback)...' 
    # since we have cookies enabled, this request will allow omniauth to parse 
    # out the auth code from the signed request in the fbsr_XXX cookie 

    # $.getJSON '/profile/auth/facebook/callback', (json) -> 
    $.get '/profile/auth/facebook/callback' if response.authResponse 
), scope: 'email' 
    # These are the permissions you are requesting 
    return 
0

当你做一个链接远程真实的,您的控制器将默认尝试渲染action.js.erb视图文件,其中行动是你路由到的行动的名称,例如show.js.erb

在该视图文件,你会写JavaScript和嵌入的Ruby很像html.erb查看文件。

当你想重新呈现在页面上的部分,你必须escape_javascript渲染方法的结果,这样就可以安全地通过一个html字符串的JavaScript。

$("#some-div").html("<%= escape_javascript render(partial: "some_content") %>"); 

请注意erb标签位于引号内部,这是为了让您最终将字符串传递给html函数。您也可以使用快捷键帮助j

$("#some-div").html("<%= j render(partial: "some_content") %>"); 

http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html

+2

那么你是对的,但是 - 不是。正如你所看到的getJSON会在我的控制器降落为JSON和js.erb简单地忽略。我想出了另一个想法。检查下面。 – Evgeny