我需要从我的 codeigniter Controller 获取数据并将其作为 ajax 调用发送到我的 View 。所以我使用这个函数向ajax函数发送数据
function vendorAccess(){
$result = $this->Admin_model->allvendor();
foreach($result as $row){
$data = $row["joinedDate"];
$now = time();
$your_date = strtotime($data);
$datediff = $now - $your_date;
$cont = round($datediff / (60 * 60 * 24));
if($cont == 85){
$response['vendorName'] = $row['vendorName'];
echo json_encode($response);
}
}
}
这会将数据发送到我的 ajax 函数。我的ajax函数是这样的
$(document).ready(function(){
$.ajax({
url: '<?php echo base_url();?>/Admin/vendorAccess',
type: 'get',
dataType:'text',
success: function(res){
console.log(res);
}
});
});
使用此代码我得到的输出如下
{"vendorName":"Cinnamon Grand"}{"vendorName":"Saloon Bhagya"}
现在我需要使用 jquery 将这两个 vendor 名称作为单独的两个名称放入我的 div 中。我在stackoverflow上搜索了这个问题,找到了一些解决方案。但这些解决方案对我不起作用。一个例子如下
$(document).ready(function(){
//$('#numOfNot').html('New');
var tmp=null;
$.ajax({
url: '<?php echo base_url();?>/Admin/vendorAccess',
type: 'get',
dataType:'json',
success: function(res){
alert(res.vendorName);
}
});
});
当我使用此功能时,请给我未定义的警报。 非常感谢您花费宝贵的时间来解决我的问题
最佳答案
您需要在 Controller 中填充一个数组,而不是每次通过循环都回显 JSON。
function vendorAccess(){
$result = $this->Admin_model->allvendor();
$names = array();
foreach($result as $row){
$data = $row["joinedDate"];
$now = time();
$your_date = strtotime($data);
$datediff = $now - $your_date;
$cont = round($datediff / (60 * 60 * 24));
if($cont == 85){
$names[] = $row['vendorName'];
}
}
echo json_encode(array('vendorName' => $names));
}
关于javascript - 使用 AJAX 函数访问 JSON 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50515825/