返回Json.Stringfy结果 [英] return Json.Stringfy result
问题描述
我有这段代码:
$.getJSON('http://myjsonurl', function(json){console.log(JSON.stringify(json.columns)); });
这将在控制台中返回我从json响应中所需的全部内容.我的目标是将此值转换为函数,以便可以在其他地方调用它. (例如:
This returns in the console all I need from my json response. My aim is to get this value into a function so that I can call it in another place. (For example :
"columns" : getColumns();
所以我正在做一个这样的功能:
So I am making a function like this :
function getColumns() {
$.getJSON('http://myjsonurl', function(json){return JSON.stringify(json.columns); });
}
console.log(getColumns()); // and then call the function in the console log expecting to see the same result as before.
但是我所得到的都是不确定的. 为什么?
But all I get is undefined. Why?
更新:
这就是我实现自己想要的方式的方式.以下代码将基于带有数据和列的json响应(数据表本身不支持的某些内容)重新初始化数据表.该代码将使用新的查询参数重新加载表格,并包含按钮plugin:
This is how I achieved what I wanted. The following code will reinitiate a datatable based on a json response with data and columns (something not supported natively from datatables). The code will reload the table with new query parameters and includes the buttons plugin :
var theurl;
theurl = "http://myjson.json";
function updateQueryStringParameternondt(key, value) {
var table = $('#datatable-buttons').DataTable();
var ajaxurl = theurl;
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = ajaxurl.indexOf('?') !== -1 ? "&" : "?";
if (ajaxurl.match(re)) {
console.log( ajaxurl.replace(re, '$1' + key + "=" + value + '$2'));
theurl = ajaxurl.replace(re, '$1' + key + "=" + value + '$2');
table.destroy();
TableManageButtons.init();
}
else {
console.log( ajaxurl + separator + key + "=" + value);
theurl = ajaxurl + separator + key + "=" + value ;
table.destroy();
TableManageButtons.init();
}
}
TableManageButtons.init();
var handleDataTableButtons = function() {
0 !== $("#datatable-buttons").length &&
$.ajax( {
url:theurl,
dataType: 'json',
success: function ( json ) {
$("#datatable-buttons").DataTable({
"data" : json.data,
"columns": json.columns,
dom: "Bfrtip",
buttons: [{
extend: "copy",
className: "btn-sm"
}, {
extend: "csv",
className: "btn-sm"
}, {
extend: "excel",
className: "btn-sm"
}, {
extend: "pdf",
className: "btn-sm"
}, {
extend: "print",
className: "btn-sm"
}],
responsive: !0
});
}
} );
},
TableManageButtons = function() {
"use strict";
return {
init: function() {
handleDataTableButtons();
}
};
}();
推荐答案
@ guest271314答案是正确的,应该指导您解决有关从getColumns
方法返回未定义的问题.
@guest271314 answer is correct and should guide you to resolve the issues regarding returning undefined from getColumns
method.
我只想在这里指出一些关键事项.
I just want to point out some key things here.
首先研究我刚才创建的 plunk .如您所见,这里的所有功能都是操纵Deferred对象(请参阅此处更多的).粗略地解释一下,Deferred对象可以注册回调,如果您喜欢多个回调,可以将它们链接起来,并通过调用它们可以广播其状态和响应.它基于promise设计,因此此类方法返回可以解析,同步或异步的promise(大多数情况下,promise在异步操作中很有用).
First investigate the plunk I created a moment ago. As you can see all the juice here is to manipulate the Deferred object (See here for more). Rougly explaining, the Deferred object can register callbacks, and if you like multiple ones, chain them, and by invoking them can broadcast their state's as well as their responses. It is based to promises design, so such methods return a promise which can be resolved, synchronous or asynchronous (most of times promises are useful in asynchronous operations).
jQuery的异步方法(如$.ajax
)返回承诺. $.getJSON
没什么不同,因为它最后会调用$.ajax
,如上所述,它会返回jQuery Deferred Promise.
jQuery's asynchronous methods, like $.ajax
return a promise. $.getJSON
is no different, as it calls $.ajax
in the end which, as mentioned returns a jQuery Deferred Promise.
有关jQuery的animation
方法,请参见下面的@ guest271314注释.
For jQuery's animation
method, see @guest271314 comment below.
有关承诺的更多信息此处.
来自文档:
返回一个Promise对象,以观察绑定到集合的某种特定类型的所有操作是否已排队.
Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished.
一个promise
,如果已解决或已拒绝,则进行处理. resolve
代表成功响应,reject
代表失败.
从文档中我们可以看到,有Deferred
对象的方法可以处理成功,失败或两者.
A promise
, when handled is either resolved or rejected. resolve
stands for success responses, as reject
stands for failures.
From documentation we can see that there are methods of Deferred
object to handle success, failure or both.
deferred.done()添加当Deferred对象为时要调用的处理程序 解决.
deferred.done() Add handlers to be called when the Deferred object is resolved.
deferred.fail()添加拒绝Deferred对象时要调用的处理程序.
deferred.fail() Add handlers to be called when the Deferred object is rejected.
deferred.always()添加当解析或拒绝Deferred对象时要调用的处理程序.
deferred.always() Add handlers to be called when the Deferred object is either resolved or rejected.
因此,让我们回到OP的问题.如您现在从代码中看到的:
So, let's get back to the OP's question. As you can see now from the code:
function getColumns() {
$.getJSON('http://myjsonurl', function(json){return JSON.stringify(json.columns); });
}
您无法知道getColumns
状态,因为您没有返回promise
.使用$.getJSON
处理程序时,您实际上在此处处理了响应而没有发出promise对象. getColumns
函数当然会返回undefined
,因为没有return
的符号,默认情况下会得到它.
There is no way for you to know the getColumns
state, because you do not return the promise
. When using the $.getJSON
handler you essentially handling the response there without emitting the promise object. The getColumns
function of course returns undefined
because there is not sign of return
and by default you get that.
关于deferred.then()
方法,使用此方法,您还可以处理一个promise,同时处理其状态和进度.在上面我发布的Plunker中的示例代码中,我不在乎进度,而只是在乎状态,因此在第一个示例中,promise是通过.then()
方法处理的,第一个函数是成功处理程序,第二个功能是失败处理程序.从他们那里返回响应本质上意味着诺言得以解决.我也答应了诺言.
Regarding the deferred.then()
method, with this you can handle a promise also, handling its state as well as its progress. In the example code in Plunker I've posted above I do not care about progress, just only the state, so in the first example the promise is handled with the .then()
method, with the first function to be the success handler and the second function to be the fail handler. Returning the response from them essentially means the promise gets resolved. I return the promise itself as well.
在注释掉的部分中,您可以看到,只有您愿意并且可以通过always
方法解析响应
In the commented out section you can see that you can return only the promise if you'd like and resolve the response in always
method
这篇关于返回Json.Stringfy结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!