Javascript 如何在成功函数中使用返回的数组?
当我尝试在视图页面上使用返回的数组数据时,它会打印未定义的not数组值。请帮帮我 我的控制器是:Javascript 如何在成功函数中使用返回的数组?,javascript,arrays,ajax,Javascript,Arrays,Ajax,当我尝试在视图页面上使用返回的数组数据时,它会打印未定义的not数组值。请帮帮我 我的控制器是: function test(){ $pro_id = $this->input->post('id',TRUE); //echo $pro_id; $cat_id = $this->input->post('cat',TRUE); $date1 = $this->input->post('dt',TRUE); $first
function test(){
$pro_id = $this->input->post('id',TRUE);
//echo $pro_id;
$cat_id = $this->input->post('cat',TRUE);
$date1 = $this->input->post('dt',TRUE);
$firstdate = date('Y-m-d', strtotime($date1));
$lastdate = strtotime(date("Y-m-d", strtotime($firstdate)) . " +6 day");
//echo $cat_id;
$data = array();
$this->load->model('inserttimemodel');
$whr = $this->inserttimemodel->gettime($pro_id,$cat_id,$firstdate,$lastdate);
$data['whr'] = $whr;
//print_r($data); //working properly
echo json_encode($data);
exit();
}
JS:
在Javascript中使用JSON.parse之前,您需要解码数据。尝试通过在成功回调中添加console.logdata语句来诊断代码,然后检查浏览器的控制台。查看PHP,您的数据应该位于data.whr.Array[whr]=>Array[0]=>Array[whr]=>1[1]=>Array[whr]=>2[2]=>Array[whr]=>3.3[3]=>Array[whr]=>6[4]=>Array[whr]=>5[5]=>Array[whr]=>8[6]=>Array[whr]=>5:30实际上,jQuery在提供数据类型:“json”时会自动解析json。
$(document).ready(function(){
$("#cat").change(function(){
var catid = $(this).val();
var id = $('#project option:selected').val();
var dt = $('#period option:selected').val();
$.ajax({
url:"<?php echo base_url();?>/timesheet/test",
data:{cat:catid,id:id,dt:dt},
type:"POST",
dataType: "json",
success:function(data){
document.getElementById("res").innerHTML = data[0];
document.getElementById("res1").innerHTML = data[1];
}
});
});
});