YaoRaoLov 2015-03-30 22:00 采纳率: 50%
浏览 40

Javascript数组:AJAX,JSON

I'm a newbee to JS , JSON and AJAX. I'm using it to develop a simple apps in my SAP env. I'm bit struck in converting the AJAX response to java array. What is have in the code is:

function addTable()
{
    var urls = new Array();
    $(document).ready(function ()
    {
        var params = getURLParam().split('?');
        $.post("GetBayDetails.htm", {url: getURLParam(), params: params[1]})
                .done(function (data)
                {
                    var url = $.parseJSON(data);
                    urls.push(JSON.parse(url));
                    $.each(url, function (i, v)
                    {
                        push.urls[i] = v.bay;
                    });
                });
    });
    alert(urls[2]);
}

but if I loop through "URLS" I do not see any value appended to the array. Please can anyone provide some help to get this fixed?

  • 写回答

1条回答 默认 最新

  • weixin_33744141 2015-03-30 23:36
    关注

    Try this. My changes are:

    1. Use the "json" dataType argument to $.post so it parses the response automatically.

    2. There's no need to use $(document).ready() inside a function that you call on demand. This is only needed when performing initial actions that have to wait for the DOM to be loaded.

    3. It's not necessary to call JSON.parse(url), as this is already parsed.

    4. The correct way to add to the urls array is urls.push(v.bay).

    5. The preferred way to initialize an array is with [], not new Array().

    6. alert(urls[2]) needs to be in the .done() function. Otherwise you're alerting before the AJAX call has completed.

    function addTable() {
        var urls = [];
        var params = getURLParam().split('?');
        $.post("GetBayDetails.htm", {url: getURLParam(), params: params[1]}, "json")
            .done(function (url) {
            $.each(url, function (i, v) {
                urls.push(v.bay);
            });
            alert(urls[2]);
        });
    
    }
    

    DEMO

    评论

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集