Javascript 如何在javascript函数中返回json对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8826632/
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
How to return json object in javascript function?
提问by ptamzz
I've this function
我有这个功能
function getTags(level){
$.getJSON("php/get-tags.php", { "parent": level }, function(json) {
return json;
});
}
I'm calling this function as
我将此函数称为
$(function(){
var tags = getTags('0');
});
The problems is, in the function getTags()
the return json
is like
问题是,在函数getTags()
中返回json
就像
{"tags":["Mathematics","Science","Arts","Engineering","Law","Design"]}
{"tags":["Mathematics","Science","Arts","Engineering","Law","Design"]}
but at var tags = getTags('0')
, catching the return value, it gets an undefined
value.
但是在var tags = getTags('0')
捕获返回值时,它会获得一个undefined
值。
Is the way I'm returning the value incorrect?
我返回值的方式不正确吗?
回答by jAndy
Like many others already correctly described, the ajax request runs asynchronous by default. So you need to deal with it in a proper way. What you can do, is to return the jXHR
object which is also composed with jQuery promise maker. That could looke like
与其他许多已经正确描述的一样,ajax 请求默认是异步运行的。因此,您需要以适当的方式处理它。您可以做的是返回jXHR
同样由 jQuery promise maker 组成的对象。那可能看起来像
function getTags(level){
return $.getJSON("php/get-tags.php", { "parent": level });
}
and then deal with it like
然后像这样处理它
$(function(){
getTags('0').done(function(json) {
// do something with json
});
});
回答by Gazler
You are trying to call an asynchronous function in a synchronous fashion.
您正在尝试以同步方式调用异步函数。
When you call getTags, the it triggers a call to your PHP page, if javascript was blocking, then your page would hang until your server responded with the JSON. You need to re-think your logic and trigger a callback.
当您调用 getTags 时,它会触发对您的 PHP 页面的调用,如果 javascript 被阻塞,那么您的页面将挂起,直到您的服务器以 JSON 响应。您需要重新思考您的逻辑并触发回调。
function getTags(level){
$.getJSON("php/get-tags.php", { "parent": level }, function(json) {
//do something with the JSON here.
});
}
回答by bububaba
If you need it to work like that, your getTags
function must return a value. It does not at the moment. You could achieve this by using $.ajax
and setting async
to false
.
如果你需要它像那样工作,你的getTags
函数必须返回一个值。目前没有。您可以通过使用$.ajax
和设置async
为false
.
回答by Rocket Hazmat
You cannot return from an AJAX call. It's asynchronous. You need to have all logic dealing with the returned data in the callback.
您不能从 AJAX 调用返回。它是异步的。您需要让所有逻辑处理回调中返回的数据。
回答by Quentin
getJSON
is asynchronous, the function that called it will have finished by the time the HTTP response gets back and triggers the callback.
getJSON
是异步的,调用它的函数将在 HTTP 响应返回并触发回调时完成。
You cannot return from it.
你无法从中返回。
Use the callback to do whatever you want to do with the data.
使用回调对数据做任何你想做的事情。