weixin_33736649 2016-09-25 19:05 采纳率: 0%
浏览 40

从jQuery Ajax返回值

I am trying to return a value from a completed jQuery Ajax call. However, instead of the JSON data, I am receiving back "undefined." How can I modify my code to get the JSON data instead of undefined?

function callback(data) {
    return data;
}

var xv = jQuery.ajax( {
    url: 'http://www.domain.com/json.php',
    dataType: 'json',
    success: function(data) {
        alert('Success.'); // This is alerted.
    },
    error: function(data) {
        alert('File could not be processed.'); // This is not alerted.
    },
    complete: function(data) {
        callback(data);
    }
});

console.log(callback()); // Getting "undefined" here instead of data.
  • 写回答

2条回答 默认 最新

  • weixin_33725126 2016-09-25 19:13
    关注

    You aren't actually storing data anywhere. All you do is reflect back whatever is given to you, just like Sterling said

    I would modify it like so:

    var globalData;
    function(callback){
      globalData = data;
    }
    

    Then console.log(globalData) and you can see the result

    评论
  • weixin_33735077 2016-09-25 19:16
    关注

    AJAX is async by default, you have your data only when you get it, that's in your success callback. Do a sync call, or use your data inside your success function.

    Your code should look like this instead:

    function doWithJson(data) {
        console.log(data);
    }
    var xv = jQuery.ajax( {
        url: 'http://www.domain.com/json.php',
        dataType: 'json',
        success: function(data) {
            doWithJson(data);
        },
        error: function(data) {
            alert('File could not be processed.');
        },
        complete: function(data) {
            /* Remove overlay */
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥80 关于海信电视聚好看安装应用的问题
  • ¥15 vue引入sdk后的回调问题
  • ¥15 求一个智能家居控制的代码
  • ¥15 ad软件 pcb布线pcb规则约束编辑器where the object matpcb布线pcb规则约束编辑器where the object matchs怎么没有+15v只有no net
  • ¥15 虚拟机vmnet8 nat模式可以ping通主机,主机也能ping通虚拟机,但是vmnet8一直未识别怎么解决,其次诊断结果就是默认网关不可用
  • ¥20 求各位能用我能理解的话回答超级简单的一些问题
  • ¥15 yolov5双目识别输出坐标代码报错
  • ¥15 这个代码有什么语法错误
  • ¥15 给予STM32按键中断与串口通信
  • ¥15 使用QT实现can通信