我正在使用ajax调用从服务器接收数据,现在我在php中以关联数组的形式存在数据首先让我向您展示格式
Array
(
[0] => Array
(
[id] => 1
[name] => Nuts
)
[1] => Array
(
[id] => 44
[name] => Dried Fruits
)
[2] => Array
(
[id] => 73
[name] => Chocolate Products
)
[3] => Array
(
[id] => 83
[name] => Seeds and Grains
)
[4] => Array
(
[id] => 91
[name] => Speciality Mixes
)
)
现在要在javascript中使用它我必须将其转换为 JSON 这里是我的PHP代码到目前为止
public function ajax_step1(){
$data=$this->Step->step1();
//print_r($data) /returns the array/
echo json_encode($data);
//prints the json object
}
这就是php返回json对象的方式!
[{"id":"1","name":" Nuts "},{"id":"44","name":"Dried Fruits "},{"id":"73","name":"Chocolate Products"},{"id":"83","name":"Seeds and Grains"},{"id":"91","name":"Speciality Mixes "}]
现在,当我尝试在javascript中使用数据时,它给了我这个错误!
此错误由mozilla
显示SyntaxError:JSON.parse:JSON数据第1行第2列的意外字符
此错误由chrome
显示位置1的JSON中的意外标记o
这是javascript代码:
$.ajax({
type: 'post',
url: '<?=base_url()?>Admin/ajax_step1',
dataType:"json",
success: function (data) {
JSON.parse(data);
for($i=0;$i<data.length;$i++){
console.log(data[$i]['name']);
}
}
});
这是我为javascript做的一点调试!
$.ajax({
type: 'post',
url: '<?=base_url()?>Admin/ajax_step1',
dataType:"json",
success: function (data) {
console.log(data);
//this is returning an array like
//Array [ Object, Object, Object, Object, Object ]
console.log(JSON.parse(data));
//this is where the error is occuring
}
});