全局变量在jquery函数外部不起作用

时间:2018-09-01 16:30:10

标签: javascript jquery

我在这里尝试对json文件进行API调用,获取数据并转换为HTML表。使用Jquery $.getJSON()函数,设法将JSON作为对象myList1获取。但是要将数据转换为HTML,我必须从jquery函数中获取JSON对象myList1。我尝试声明一个全局变量并将数据移至globallist。但是globallist在jquery $.getJSON()之外无法正常工作。 在$ .getJSON()函数外部调用全局变量globallist时,这是控制台日志。

console globallist not showing

这是globallist函数内部称为$.getJSON()的控制台日志。 console globallist shown

以下是我的Javascript代码:

<script type="text/javascript">
var globallist;

    $.getJSON('http://starlord.hackerearth.com/movieslisting', function(myList1) {
    //data is the JSON string
    globallist=myList1;
    // console.log(globallist); 
});

   console.log(globallist);
</script>

在这段代码之后,我必须将globallist传递给js函数buildHtmlTable(selector)才能将数据隐蔽到HTML表中。 我已经尝试了一切,请帮忙。

0 个答案:

没有答案