将json数据转换为javascript数组

时间:2017-07-24 07:32:29

标签: javascript jquery arrays json

    $.ajax({
        type: "POST",
        url: "Default2.aspx/myMethod",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function OnSuccess(response) {
            var str = response.d;
            var jsonObj = JSON.parse(str);
            for(i=0;i<jsonObj.length;i++)
            {
                jsonObj[i]="{"+jsonObj[i]+"}"
            }
            jsonObj = "[" + jsonObj + "]";
        },
        failure: function (response) {
            alert(response.d);
        }
    });

我在jsonObj中收到的是图像路径的javascript数组。我将此数组传递给图像滑块以显示图像,但它显示未定义,即不显示图像 jsonObj的结果是

[{'src: ../img/kota-image/11.jpg'},{'src: ../img/kota-image/12.jpg'},{'src: ../img/kota-image/13.jpg'},{'src: ../img/kota-image/14.jpg'},{'src: ../img/kota-image/15.jpg'},{'src: ../img/kota-image/197.jpg'},{'src: ../img/kota-image/2706.jpg'},{'src: ../img/kota-image/9.jpg'},{'src: ../img/kota-image/DSC_0825.JPG'},{'src: ../img/kota-image/kota.jpg'}]

我的图片滑块是

jR3DCarousel = $('.jR3DCarouselGallery').jR3DCarousel({
        width: $(window).width(),       /* largest allowed width */
        height: 670,        /* largest allowed height */
        slides: jsonObj/* array of images source */,
        "animationDuration": 1500,
        "animationInterval": 2500,
    });

3 个答案:

答案 0 :(得分:1)

我想,你不需要这个循环:

.png

for(i=0;i<jsonObj.length;i++) { jsonObj[i]="{"+jsonObj[i]+"}" } jsonObj = "[" + jsonObj + "]"; 已经是一个数组。

尝试以下代码:

var jsonObj = JSON.parse(str);

如果你想将对象转换为纯数组,你可以这样做。

$.ajax({
    type: "POST",
    url: "Default2.aspx/myMethod",
    data: '{}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function OnSuccess(response) {
        var str = response.d;
        var jsonObj = JSON.parse(str); 
        console.log( jsonObj  );
    },
    failure: function (response) {
        alert(response.d);
    }
});

答案 1 :(得分:0)

您的json似乎格式不正确。 从

改变它
[{'src: ../img/kota-image/11.jpg'},{'src: ../img/kota-image/12.jpg'}]

[{'src': '../img/kota-image/11.jpg'},{'src':
 '../img/kota-image/12.jpg'}]

答案 2 :(得分:0)

你必须像这样使用

[{'src': '../img/kota-image/11.jpg'},{'src': '../img/kota-image/12.jpg'},{'src': '../img/kota-image/13.jpg'},{'src': '../img/kota-image/14.jpg'},{'src': '../img/kota-image/15.jpg'},{'src': '../img/kota-image/197.jpg'},{'src': '../img/kota-image/2706.jpg'},{'src': '../img/kota-image/9.jpg'},{'src': '../img/kota-image/DSC_0825.JPG'},{'src': '../img/kota-image/kota.jpg'}]