填充 javascript 变量然后加载脚本

Populate javascript variable and then load scripts

在我的 MVC 应用程序中,我试图在加载脚本之前填充两个 javascript 变量。但是我不断收到错误消息,我的变量未在加载 javascript 文件之前设置。我一直在兜圈子试图弄清楚这一点。

<script type="text/javascript">
        $(document).ready(function () {
            var applicationId = "@Constants.SquareUpPaymentInfo.AppID";
            var locationId = "@Constants.SquareUpPaymentInfo.LocationID";
            jQuery.getScript('https://js.squareup.com/v2/paymentform')
                .done(function () {
                    jQuery.getScript('@Url.Content("~/Content/JS/sqpaymentform.js")')
                        .fail(function () {
                            alert('Failed');
                        })
                })
                .fail(
                function () {
                        alert('There was a connection issue for the payment form library. ');
                    });
        });
</script>

sqpaymentform.js 加载但它需要设置 applicationID 和 locationID 但它认为由于某种原因它们没有设置但我可以很容易地看到它们是在 chrome 开发者屏幕中设置的.

您将 applicationIdlocationId 声明为局部变量。脚本需要它们是全局变量,所以在函数外声明它们。

<script type="text/javascript">
var applicationId = "@Constants.SquareUpPaymentInfo.AppID";
var locationId = "@Constants.SquareUpPaymentInfo.LocationID";

$(document).ready(function() {
  jQuery.getScript('https://js.squareup.com/v2/paymentform')
    .done(function() {
      jQuery.getScript('@Url.Content("~/Content/JS/sqpaymentform.js")')
        .fail(function() {
          alert('Failed');
        })
    })
    .fail(
      function() {
        alert('There was a connection issue for the payment form library. ');
      });
});
</script>