$ .getJSON的外部访问JSON数据() [英] Access json data outside of $.getJSON()
本文介绍了$ .getJSON的外部访问JSON数据()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$(document).ready(function () {
var value = getParmsVals()["search"];
$.getJSON('/api/search/GetQuestionByKey/' + value, function (jsonData) {
$(jsonData).each(function (i, item) {
var name = getAuthorName(item.userId);
});
});
});
function getAuthorName(userId) {
var fullname = "default";
$.getJSON('/api/search/GetUserById/' + userId, function (jsonData) {
fullname = jsonData.firstname + " " + jsonData.lastname;
});
return fullname;
}
我试图通过调用getAuthorName方法来访问全名变量,但我无法得到正确的值。它总是给我的价值默认。
I'm trying to access the fullname variable by calling the getAuthorName method but I couldn't get the correct value. It's always giving me the value "default".
推荐答案
您不会收益
从异步方法,你可以看到,这是行不通的!你需要的是一个回调函数,考虑:
You wouldn't return
from an async method, as you can see, it doesn't work! What you need is a callback function, consider:
function getAuthorName(userId, callback) {
var fullname = "default";
$.getJSON('/api/search/GetUserById/' + userId, function (jsonData) {
fullname = jsonData.firstname + " " + jsonData.lastname;
callback(fullname);
});
}
注意我们是如何通过在回调
,然后在你的get调用月底打电话吗?现在,调用此方法像这样:
Notice how we pass in callback
and then call it at the end of your get call? Now call this method like so:
getAuthorName(userID, function(name) {
console.log(name);
});
现在,你有机会获得全名
在回调函数!
这篇关于$ .getJSON的外部访问JSON数据()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文