在我的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开发人员屏幕中设置。
答案 0 :(得分:3)
您将applicationId
和locationId
声明为局部变量。脚本需要它们是全局变量,因此请在函数外部声明它们。
<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>