javascript - js访问ajax获取的json数据
伊谢尔伦
伊谢尔伦 2017-04-11 13:09:53
0
2
313

我不想像这样处理取得的json数据,有时候在success里要写较多代码

$.ajax({
    type: "get",
    dataType: "json",
    url: 'skin/data/winner.json',
    success: function (data) {
         var jsonData = data;
         var html = buildHtml(jsonData);
        $("ul.infoList").html(html);
        $(".topLoop").slide({
            mainCell: ".bd ul",
            effect: "topMarquee",
            vis: 6,
            interTime: 40,
            autoPlay: true
        });
    }
}); 

我想把$.ajax取得的json数据在外部获取调用,打印出结果是undefined。有没有办法可以在外部访问到ajax取得的data值

$.ajax({
    type: "get",
    dataType: "json",
    url: 'skin/data/winner.json',
    success: function (data) {
       var jsonData = data;
       console.log('data--'+jsonData);
       return jsonData;        
    }
});
console.log(jsonData);  //undefined

var html = buildHtml(jsonData);
$("ul.infoList").html(html);
$(".topLoop").slide({
    mainCell: ".bd ul",
    effect: "topMarquee",
    vis: 6,
    interTime: 40,
    autoPlay: true
});

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回覆(2)
阿神

您好,由于$.ajax函数的async属性默认为true,即异步请求,并且您声明的jsonData是局部变量,所以jsonData输出结果为undefined。如果您想外部访问到ajax响应值,有两种方法:

方法一:指定一个回调函数,示例如下:

$.ajax({
    type: "get",
    dataType: "json",
    url: 'skin/data/winner.json',
    success: callBack
});
// 回调函数
function callBack(jsonData) {
    // 在这里做其他处理
    var html = buildHtml(jsonData);
    $("ul.infoList").html(html);
    $(".topLoop").slide({
        mainCell: ".bd ul",
        effect: "topMarquee",
        vis: 6,
        interTime: 40,
        autoPlay: true
    });
}

方法二:改成同步请求,示例如下:

var jsonData; // 全局变量
$.ajax({
    type: "get",
    dataType: "json",
    async: false,
    url: 'skin/data/winner.json',
    success: function (data) {
       jsonData = data;     
    }
});
console.log(jsonData);

var html = buildHtml(jsonData);
$("ul.infoList").html(html);
$(".topLoop").slide({
    mainCell: ".bd ul",
    effect: "topMarquee",
    vis: 6,
    interTime: 40,
    autoPlay: true
});
PHPzhong
function getWinner(json) {
    var html = buildHtml(json);
    $("ul.infoList").html(html);
}

function setSlider() {
    $(".topLoop").slide({
        mainCell: ".bd ul",
        effect: "topMarquee",
        vis: 6,
        interTime: 40,
        autoPlay: true
    });
}

$.getJSON('skin/data/winner.json')
    .done(getWinner)
    .done(setSlider);

大概是这个意思?

(手机码的排版不太好抱歉~)

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!