使用来自Ajax响应的变量 [英] Use variable from Ajax response

查看:95
本文介绍了使用来自Ajax响应的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件:

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才可用.如何使此代码起作用?

In example.html, I need console.log(alpha) to output "data". I make an Ajax request to example1.html, and update the contents of my div with the returned html. The constant alpha isn't useable until new Dropzone() succeeds. How can I make this code work?

推荐答案

一种选择是使您的alpha变量成为全局变量.

One option is to make your alpha variable global.

您在成功函数中声明了alpha变量,因此只能在其中使用该变量.

You declared your alpha variable inside success function so you can only use that variable inside it.

<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>

现在您可以通过以下方式访问它

Now you can access it as

$(document).on("click", "button", function() {
    console.log(alpha); // Should print "data", 
});

这篇关于使用来自Ajax响应的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆