我想将json对象复制到javascript数组,
{
"profiledata1":{"id":0,"music":0,"image_x":130,"image_y":155,"mouth_x":0,"mouth_y":-28.125,"active":true,"default":false},
"profiledata2":{"id":1,"music":0,"image_x":130,"image_y":155,"mouth_x":0,"mouth_y":0,"active":true,"default":false},
"profiledata3":{"id":2,"music":0,"image_x":0,"image_y":0,"mouth_x":0,"mouth_y":0,"active":false,"default":false},
"profiledata4":{"id":3,"music":0,"image_x":0,"image_y":0,"mouth_x":0,"mouth_y":0,"active":false,"default":false},
"profiledata5":{"id":4,"music":0,"image_x":0,"image_y":0,"mouth_x":0,"mouth_y":0,"active":false,"default":false},
"upload":"http:\/\/localshost\/",
"format":"jpeg","status":1 }
这是我通过ajax调用some.php时返回的json对象, 我想在java脚本中将profiledata1复制到userdata_arr [0],将profiledata2复制到userdata_arr [1],将profiledata3复制到userdata_arr [2],将profile4data复制到userdata_arr [3],将profiledata5复制到userdata_arr [5]。 我的java脚本如下,
$.ajax({
type: "POST",
url: "some.php",
data: {action:'load',
id:7}
}).done(function(o) {
var data = $.parseJSON(o);
if (!data || data === null) {
someError(true);
}else{
if(data.status==true){
userdata_arr[0] = data.profiledata1[0];
userdata_arr[1] = data.profiledata2[0];
userdata_arr[2] = data.profiledata3[0];
userdata_arr[3] = data.profiledata4[0];
userdata_arr[4] = data.profiledata5[0];
uploadDir = data.upload;
imgFormat = data.format;
somefunction();
}else{
someError(true);
}
}
});
当我执行此脚本时,我将userdata_arr视为未定义!请帮我纠正这个问题。 我也在这里附上some.php,
<?php
if ($_POST['action']=='load') {
$uid=$_POST['id'];
header("content-type:application/json");
// fetch contents from db with $uid;
$query = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($query)) {
$prof1 = $row['prof1'];
$prof2 = $row['prof2'];
$prof3 = $row['prof3'];
$prof4 = $row['prof4'];
$prof5 = $row['prof5'];
}
$jp1 = json_decode($prof1, 1);
$jp2 = json_decode($prof2, 1);
$jp3 = json_decode($prof3, 1);
$jp4 = json_decode($prof4, 1);
$jp5 = json_decode($prof5, 1);
echo json_encode($dta = array('profile1data' =>json_decode($prof1),'profile2data' =>json_decode($prof2),'profile3data' =>json_decode($prof3),'profile4data' =>json_decode($prof4),'profile5data' =>json_decode($prof5) ,'upload' =>'http://localhost/img/', 'format' =>'jpeg', 'status' =>1 )); ?>
提前致谢!
答案 0 :(得分:2)
那是因为你还没有宣布你的userdata_arr
。要修复它,请在使用之前声明您的数组/对象变量。在else
代码块中,执行以下操作:
else{
var userdata_arr = {}// declare your object
if(data.status==true){ //proceed to use your already-declared object, also notice the quote marks surrounding the object members/indexes
userdata_arr["0"] = data.profiledata1[0];
userdata_arr["1"] = data.profiledata2[0];
userdata_arr["2"] = data.profiledata3[0];
userdata_arr["3"] = data.profiledata4[0];
userdata_arr["4"] = data.profiledata5[0];
uploadDir = data.upload;
imgFormat = data.format;
somefunction();
}else{
someError(true);
}
}