【问题标题】:send json responses but with lots of data发送 json 响应但有大量数据
【发布时间】:2020-09-06 08:22:15
【问题描述】:

我有一个问题,我发送到视图的数据与查询生成的数据量不匹配。仅显示单个数据。

这是我的功能:

function lokasi_ajax() {
		var kode_lokasi = $('#kode_lokasi').val();

		$.ajax({
			url : '<?= base_url() ?>index.php/asset/asset_dijual_proses/lokasi_ajax',
			data: 'kode_lokasi='+kode_lokasi,
			success : function (data) {
				var json = data;
				value = JSON.parse(json);

				console.log(value.kode_aset);

			}
		});
	}

这是我控制器上的方法:

function lokasi_ajax()
	{
		$kode_lokasi = $_GET['kode_lokasi'];
		$data =array();

		$query = $this->db->query("SELECT id_reg, item_lokasi, item_barang FROM asset_item 
			WHERE item_lokasi= '$kode_lokasi'");
		foreach ($query->result() as $row) {
			$data = array(
				'kode_aset' => $row->id_reg,
				'item_lokasi' => $row->item_lokasi,
				'item_barang' => $row->item_barang 
			);
		}
		echo json_encode($data);
	}

应该生成的数据量如下图:

result data from dbms

但是从响应 json 中只显示一个这样的数据: json response result

【问题讨论】:

  • 因为$data 每次迭代都会被覆盖,因此您只能得到一个(最后一行),将其更改为$data[] = 以不断推入$data 数组

标签: javascript php json ajax codeigniter


【解决方案1】:

您的 foreach 循环重新分配数据。您需要将其添加到数组中。

foreach ($query->result() as $row) {
    $data[] = array(
        'kode_aset' => $row->id_reg,
        'item_lokasi' => $row->item_lokasi,
        'item_barang' => $row->item_barang 
    );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2013-01-17
    • 2017-08-02
    • 2017-11-03
    • 1970-01-01
    • 2016-09-13
    • 2013-11-24
    相关资源
    最近更新 更多