javascript jQuery。将 JSON 作为结果分配给变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4546339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery. Assign JSON as a result to a variable
提问by Sergei Basharov
I use this helper function to receive JSON results for my requests:
我使用这个辅助函数来接收我的请求的 JSON 结果:
function getData(url) {
$.get(url,
function(data) {
response = data;
return response;
}, 'application/json');
}
I give it some string as a part of url from my web application, like '/api/getusers', so it looks like getData('/api/getusers'). Now I need that string result containing JSON data that I receive from the url to be assigned to my variable, so it would look like this: var result = getData('/api/getusers'). Then I will process this JSON data. The problem is with the returning the response variable. It's undefined. Thanks!
我给它一些字符串作为来自我的 web 应用程序的 url 的一部分,比如“/api/getusers”,所以它看起来像getData('/api/getusers'). 现在我需要包含JSON数据,我从URL接收将被分配给我的变量,所以它看起来像这样的字符串结果:var result = getData('/api/getusers')。然后我将处理这个 JSON 数据。问题在于返回响应变量。它是未定义的。谢谢!
回答by Valerij
try this
试试这个
function getData(url) {
var data;
$.ajax({
async: false, //thats the trick
url: 'http://www.example.com',
dataType: 'json',
success: function(response){
data = response;
}
});
return data;
}
回答by Nick Craver
It's an asynchronous operation, meaning that function(data) { ... }runs laterwhen the response from the server is available, long after you returned from getData(). Instead, kick off whatever you need from that function, for example:
这是一个异步操作,这意味着当服务器的响应可用时稍后function(data) { ... }运行,在您从. 相反,从该函数中启动您需要的任何内容,例如:getData()
function getData(url, callback) {
$.get(url, callback, 'application/json');
}
Then when you're calling it, pass in a function or reference to a function that uses the response, like this:
然后,当您调用它时,传入一个函数或对使用响应的函数的引用,如下所示:
getData("myPage.php", function(data) {
alert("The data returned was: " + data);
});
回答by Жасулан Бердибеков
Use $.ajax
使用 $.ajax
$.ajax({
url: 'http://www.example.com',
dataType: 'json',
success: function(data){
alert(data.Id);
}
});

