JSON到字符串Javascript
下面的代码似乎无法将JSON结果连接成字符串,有人知道为什么吗JSON到字符串Javascript,javascript,arrays,json,string,Javascript,Arrays,Json,String,下面的代码似乎无法将JSON结果连接成字符串,有人知道为什么吗 function wordCloud(filename) { var file = filename; var text = " "; $.getJSON(file, function(data) { $.each(data, function(key, val) { text = text.concat(val.toString()); });
function wordCloud(filename)
{
var file = filename;
var text = " ";
$.getJSON(file, function(data) {
$.each(data, function(key, val) {
text = text.concat(val.toString());
});
});
console.log(text);
}
谢谢它可以很好地执行,只需在get语句中添加
console.log
,否则,getJSON代码将异步运行,同时当控件到达console.log语句时,text
仍然为空。因此,您必须按以下方式修改代码:
$.getJSON(file, function(data) {
$.each(data, function(key, val) {
text = text.concat(val.toString());
});
console.log(text);
});
console.log(文本)在调用成功回调之前执行代码>。Ajax是异步的。请看一下。啊,那是不是意味着它还在工作?我应该包括某种延迟吗?不,应该将console.log(text)
放在回调中。如果我想稍后在另一个例程中使用text变量,我是否必须使用延迟?不过谢谢你的帮助:)尤其是你应该阅读我链接到的另一个问题。又来了:。