gpt4 book ai didi

javascript - Ajax 调用在 CodeIgniter 中返回 int 而不是 string

转载 作者:可可西里 更新时间:2023-10-31 23:39:37 24 4
gpt4 key购买 nike

这是我的模型。 get items 会根据location从数据库中获取item name

class Itemsale_db extends CI_Model

public function getItems($userid,$loc)
{
$sql = "SELECT DISTINCT Name from itransfile where";

if (is_numeric($loc))
$sql .= " location_id = ".$loc;
else
$sql .= " location_id IN(SELECT location_id FROM client_locations where client_id = " .$userid. ")";

$query = $this->db->query($sql);
$item = $query->result_array();
return $item;
}
}

这是我的 Controller 。 getItemsAjax 将调用模型并返回 json 编码的数组以供查看。

class ItemSale extends CI_Controller {

public function getItemsAjax($userid,$locid)
{
$this->load->model('itemsale_db');
header('Content-Type: application/x-json; charset=utf-8');
$item = $this->itemsale_db->getItems($userid,$locid);
echo json_encode($item);
}
}

这是Javascript。 loc为位置选择框,items为项目选择框

$(document).ready(function(){
$('#loc').change(function(){
$("#items > option").remove();
var opt = $('<option />');
opt.val('All');
opt.text('All');
$('#items').append(opt);
var loc_id = $('#loc').val();
var userid = "<?php echo $this->session->userdata('userid'); ?>";

$.ajax({
type: "POST",
url: "<?php echo base_url()?>" + "index.php/itemsale/getItemsAjax/"+loc_id + "/"+userid,

success: function(item)
{
$.each(item,function(Name)
{

var opt = $('<option />');
opt.val(Name);
opt.text(Name);
$('#items').append(opt);
});
}

});

});
});

Ajax 调用返回整数列表而不是项目名称。 enter image description here enter image description here

控制台日志(项目) enter image description here

最佳答案

您的代码问题是这样的($.each 函数的格式不正确)。

First argument should be index and second should be value in $.each callback.

这是 $.each 回调的正确格式 Function( Integer indexInArray, Object value )

在ajax中成功使用以下代码:

$.each(item,function(index,Name) {//added index first and then value
var opt = $('<option />');
opt.val(Name);
opt.text(Name);
$('#items').append(opt);
});

注意:当您在每个回调中仅使用单个参数时,它会处理 NameIndex

关于javascript - Ajax 调用在 CodeIgniter 中返回 int 而不是 string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30321091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com