return Json.Stringfy 结果

return Json.Stringfy result

我有这段代码:

$.getJSON('http://myjsonurl', function(json){console.log(JSON.stringify(json.columns)); });

控制台中的这个 returns 是我 json 响应所需要的。我的目标是将这个值放入一个函数中,以便我可以在另一个地方调用它。 (例如:

"columns" : getColumns();

所以我正在制作这样的函数:

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.

但我得到的只是未定义的。 为什么?

更新:

这就是我实现目标的方式。以下代码将根据包含数据和列的 json 响应重新启动 datatable(datatables 本身不支持)。该代码将使用新的查询参数重新加载 table 并包含按钮插件:

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, '' + key + "=" + value + ''));
    theurl = ajaxurl.replace(re, '' + key + "=" + value + '');
    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();
            }
        };
    }();

您的 getColumns() 函数需要 return 变量,目前它只是被 return 编辑到函数而不是输出。试试这个: {

function getColumns() {
    var ret;
    $.getJSON('http://myjsonurl', function(json){
          ret = JSON.stringify(json.columns); 
          });
    return ret;
    }

正如@MiguelBolan 指出的那样,getColmuns() 没有返回任何值。 return $.getJSON() 来自 getColumns();使用 .then() 访问从异步函数返回的值

function getColumns() {
  return $.getJSON("http://myjsonurl");
}

getColumns().then(function(json) {
  console.log(JSON.stringify(json.columns))
}
// handle errors
, function err(jqxhr, textStatus, errorThrown) { 
    console.log(textStatus, errorThrown)
}; 

@guest271314 答案是正确的,应该会指导您解决有关 returning undefined from getColumns 方法的问题。

我只想在这里指出一些关键的事情。

首先调查 plunk I created a moment ago. As you can see all the juice here is to manipulate the Deferred object (See here 了解更多)。粗略地解释一下,Deferred 对象可以注册回调,如果您喜欢多个回调,将它们链接起来,通过调用它们可以广播它们的状态和响应。它基于承诺设计,因此此类方法 return 可以解决同步或异步的承诺(大多数时候承诺在异步操作中很有用)。

jQuery 的异步方法,就像 $.ajax return 一个承诺。 $.getJSON 没有什么不同,因为它最后调用了 $.ajax,如前所述,return 是一个 jQuery 延迟承诺。

对于jQuery的animation方法,请参阅下面的@guest271314评论。

更多承诺 here

来自文档:

Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished.

A promise,处理后是 已解决已拒绝resolve 代表成功响应,因为 reject 代表失败。 从文档中我们可以看到 Deferred 对象有处理成功、失败或两者的方法。

deferred.done() Add handlers to be called when the Deferred object is resolved.

deferred.fail() Add handlers to be called when the Deferred object is rejected.

deferred.always() Add handlers to be called when the Deferred object is either resolved or rejected.

所以,让我们回到 OP 的问题。正如您现在从代码中看到的那样:

function getColumns() {
    $.getJSON('http://myjsonurl', function(json){return JSON.stringify(json.columns); });
}

您无法知道 getColumns 状态,因为您不 return promise。使用 $.getJSON 处理程序时,您实际上是在处理那里的响应而不发出 promise 对象。 getColumns 函数当然是 returns undefined 因为没有 return 的符号,默认情况下你会得到它。

关于 deferred.then() 方法,你也可以用它来处理承诺,处理它的状态和进度。在上面发布的 Plunker 中的示例代码中,我不关心进度,只关心状态,因此在第一个示例中,promise 是使用 .then() 方法处理的,第一个函数是成功处理程序第二个函数是失败处理程序。从他们那里返回响应本质上意味着承诺得到解决。我 return 承诺本身也是如此。

在注释掉的部分中,您可以看到您可以 return 仅在您愿意的情况下承诺并解决 always 方法中的响应