2016-04-22 86 views
0

我正在嘗試學習JavaScript,並遇到了因使用變量通過多個函數工作的牆。Javascript全局變量簡單解決方案

通過瀏覽文檔和計算器大多數表決答案,涉及到全局變量以及如何通過多個函數有效地處理它們。

我發現很少或沒有簡單的解決方案。

任何一種靈魂都能夠糾正這段完整的代碼如何正常工作?需要

變量「TTL」和「味精」如果你要回應來自Ajax請求,那麼你可以返回從「Ajax」的功能中的「通知」功能

<script src="js/jquery.js"></script> 
<script src="js/bootstrap-notify.js"></script> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     // Global variables ttl and msg needed ? 
     var ttl = null; 
     var msg = null; 

     // Make an ajax call to json file. 
     $.ajax({ 
      url: "lastorder.json", 
      dataType: "json", 
      // Parse title and message from json. 
      success: function(data) { 
       ttl = data.title; 
       msg = data.message; 
      } 
     }); 
     // Notify function displays a title and message that was parsed from json file 
     $.notify({ 
      icon: 'img/avatar.jpg', 
      title: ttl, 
      message: msg 
     },{ 
      type: 'minimalist', 
      delay: 3000, 
      icon_type: 'image', 
      template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' + 
       '<img data-notify="icon" class="img-circle pull-left">' + 
       '<span data-notify="title">{1}</span>' + 
       '<span data-notify="message">{2}</span>' + 
      '</div>' 
     }); 

    }); 
</script> 
+0

您可以將您的'$ .notify'代碼到'success'回調?還是有一個理由需要在它之外? –

+0

你是否在通知函數中獲得兩個變量的空值? –

+0

邁克,這樣做的工作,但我不能在功能內嵌套函數,當我將添加更多的事情要做。我檢查了這個[參考](http://stackoverflow.com/questions/9085839/surprised-that-global-variable-has-undefined-value-in-javascript)因爲我將需要使用超過ttl和味精超過只是'$ .notify'函數,所以有一個具體的解決方案來使用變量很重要。 –

回答

0

通過在ajax請求成功執行後獲取這些數據。 由於ajax是異步調用,等待響應的代碼在收到響應時已經執行。 所以你不會在通知函數中得到由ajax響應返回的確切值。

所以,爲了使用由ajax響應返回的值,必須調用方法爲ajax的success()方法中的notify函數。

refer this SO question

1

如果你想嘗試@MikeC解決方案:

$(document).ready(function() { 
     // Global variables ttl and msg needed ? 
     var ttl = null; 
     var msg = null; 

     // Notify function displays a title and message that was parsed from json file 
     function notify(data) { 

      ttl = data.title; 
      msg = data.message; 

      $.notify({ 
       icon: 'img/avatar.jpg', 
       title: ttl, 
       message: msg 
      }, { 
       type: 'minimalist', 
       delay: 3000, 
       icon_type: 'image', 
       template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' + 
       '<img data-notify="icon" class="img-circle pull-left">' + 
       '<span data-notify="title">{1}</span>' + 
       '<span data-notify="message">{2}</span>' + 
      '</div>' 
      }); 

     } 

     // Make an ajax call to json file. 
     $.ajax({ 
      url: "lastorder.json", 
      dataType: "json", 
      // Parse title and message from json. 
      success: notify 
     }); 

    });