我有两个文件:
example.html:
<div class="my-div"></div>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "example1.html",
type: "get",
success: function(response) {
$(".my-div").html(response);
}
});
$(document).on("click", "button", function() {
console.log(alpha); // Should print "data",
});
});
</script>
example1.html:
<button></button>
<script type="text/javascript">
$(document).ready(function() {
var myDropzone = new Dropzone("", {
success: function(file, response) {
const alpha = "data";
}
});
});
</script>
在example.html中,我需要console.log(alpha)
来输出“数据”。我向 example1.html
发出 Ajax 请求,并使用返回的 html 更新 div 的内容。在 new Dropzone()
成功之前,常量 alpha
不可用。我怎样才能让这段代码工作?
最佳答案
一种选择是将您的 alpha
变量设置为全局变量。
您在 success 函数中声明了 alpha
变量,因此您只能在其中使用该变量。
<button></button>
<script type="text/javascript">
const alpha; /* Init it here */
$(document).ready(function() {
var myDropzone = new Dropzone("", {
success: function(file, response) {
alpha = "data"; /* Assign the value here */
}
});
});
</script>
现在您可以通过以下方式访问它
$(document).on("click", "button", function() {
console.log(alpha); // Should print "data",
});
关于javascript - 使用 Ajax 响应中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48555378/