大家好我有一个在codeigniter中开发的网站。 在某些函数中,我必须从mysql中检索数据并在javascript中打印结果,因为它是一个ajax调用。
这是我检索数据的php函数:
public function getCityByNameOnly($name) {
$query = $this->db->query('SELECT * FROM city WHERE name LIKE "%'.$name.'%" ');
$city = array();
foreach ($query->result() as $row)
array_push($city, $row);
return json_encode($city);
}
}
这是我的ajax电话:
$('#ricerca-ajax').keyup(function(){
var val = $(this).val();
if (val.length>2){
var site_url_city ="<?php echo(site_url('/city/get_city_by_text')); ?>";
$.ajax({
url: site_url_city,
type: "POST",
data: {search: val},
dataType: "text",
success: function(data) {
console.log(data);
for(var i=0;i<data.length;i++)
{
$('#msgid').append(data[i].name_en + '<br> ');
}
}
});
}
})
我将结果附加到div中,但始终未定义。 这是我创建的json的console.log:
{"id":"125","name_it":"Lèsina (Hvar)","name_en":"Hvar","nation_id":"23","region_id":"0","active":"1"},{"id":"127","name_it":"Trogir (Traù)","name_en":"Trogir","nation_id":"23","region_id":"0","active":"1"},{"id":"1088","name_it":"Città del Capo","name_en":"Cape Town","nation_id":"101","region_id":"0","active":"1"}]
如何在javascript中将此json打印到我的成功函数中? 感谢
答案 0 :(得分:4)
更改ajax中的datatype:"json"
将解决问题
$('#ricerca-ajax').keyup(function(){
var val = $(this).val();
if (val.length>2){
var site_url_city ="<?php echo(site_url('/city/get_city_by_text')); ?>";
$.ajax({
url: site_url_city,
type: "POST",
data: {search: val},
dataType: "json",
success: function(data) {
console.log(data);
for(var i=0;i<data.length;i++)
{
$('#msgid').append(data[i].name + '<br> ');
}
}
});
}
})