jQuery的。分配JSON作为其结果,以一个可变 [英] jQuery. Assign JSON as a result to a variable
问题描述
我用这个辅助函数接收JSON结果我的要求:
I use this helper function to receive JSON results for my requests:
function getData(url) {
$.get(url,
function(data) {
response = data;
return response;
}, 'application/json');
}
我给它一些字符串的URL从我的web应用程序的一部分,像/ API / getusers',所以它看起来像的getData('/ API / getusers')
。现在我需要包含我从URL接收分配给我的变量的JSON数据串,所以它看起来是这样的: VAR的结果=的getData('/ API / getusers')
。然后,我会处理这个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!
推荐答案
这是一个异步操作,这意味着功能(数据){...}
运行的后来当来自服务器的响应可用,您可以从返回后不久
的的getData()。相反,打完折无论你从那个功能所需要的,例如:
It's an asynchronous operation, meaning that function(data) { ... }
runs later when 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 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);
});
这篇关于jQuery的。分配JSON作为其结果,以一个可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!