[英]converting json data to javascript array
$.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,
});
我認為,您不需要此循環:
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);
}
});
如果要將對象轉換為純數組,則可以通過這種方式進行。
success: function OnSuccess(response) {
var str = response.d;
var data = JSON.parse(str);
var jsonObj = $.map(data, function(value, index) {
return [value];
});
console.log(jsonObj );
}
您的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'}]
你必須這樣使用
[{'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'}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.