【问题标题】:How to set window.variable in jquery ajax callback in coffeescript如何在coffeescript的jquery ajax回调中设置window.variable
【发布时间】:2013-03-17 15:31:29
【问题描述】:

这个项目使用 Rails + Backbone-on-rails。 我已经尝试过这个&那个......但我仍然无法在响应回调中设置全局变量。这是我尝试做的:
1) 在主干初始化的地方初始化变量

$(document).ready ->
  window.current_user = null
  Notes.initialize()

2) 设置回调

  authorize: ->
    jQuery.ajax(
      type: 'POST'
      url: '/api/sessions.json'
      wait: true
      data:
        email: @get('email')
        password:  @get('password')
    ).success( (response) ->
      exports = this
      exports.current_user = response
      window.current_user = response
      `window.current_user = response`

3) 最后执行这个方法:

loginUser: (e)->
    e.preventDefault()
    if !@validateField('password') && !@validateField('email')
      return false
    @model.attributes  = @readAttributes()
    @$('#errors').text()
    @model.authorize() # call a method defined above
    console.warn window.current_user
    if window.current_user
      @$('#errors').text('You\'ve successfuly logged in ' )
    else
      @$('#errors').text('Wrong email/password!')

console.warn window.current_user 的输出是null
我应该如何使用这个全局变量?
PS。服务器的响应是正确的。

【问题讨论】:

    标签: javascript jquery ajax backbone.js coffeescript


    【解决方案1】:

    只需将 1) 更改为即可解决

    $(document).ready ->
      window.current_user =
        name: ""
        company: ""
        created_at: ""
        email: ""
        facebook: ""
        id: ""
        license_id: ""
        linkedin: ""
        password_digest: ""
        phone: ""
        title: ""
        twitter: ""
        updated_at: ""
        web: ""
      Notes.initialize()  
    

    还没找到其他方法...

    【讨论】:

      猜你喜欢
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多