jquery ajax擷取php返回json資料產生select下拉框

來源:互聯網
上載者:User

例子

 代碼如下 複製代碼

<script type="text/javascript" language="JavaScript">
function select(){
var pro_id = $("#pro").val();
$.ajax({
'url':'cartage_fee.php?act=ajaxGetCity&region_id='+pro_id,
'type':'post',
'dataType':'json',
success:function(msg){
$("#city").html('');
$.each(msg,function(index,val){
$("#city").append('<option value='+val.region_id+' >'+val.region_name+'</option>');
})
}
});
}
</script>

php返回json資料

 代碼如下 複製代碼

while($row = $db->fetch_array($query)){

$row['uname'] = mb_convert_encoding($row['uname'],'utf-8','gbk');

$row['content'] = mb_convert_encoding($row['content'],'utf-8','gbk');

$com[] = $row;

 }

echo json_encode($com);

使用json_encode()處理數組,需要先把數組中的漢字內容進行編碼轉換,將GBK的編碼轉換為UTF-8
注意:從utf-8資料庫中取出的值不需要進行轉化

轉換後輸出json格式為:

 代碼如下 複製代碼

{"name":"\u674e\u662d\u8c15","nick":"\u5929\u5802\u7693\u6708","contact":{"email":"zhaoyulee@126.com","website":"http:\/\/www.111cn.net"},"sex":"\u7537"}

如果我們想轉換直接顯示中文可如下操作

 代碼如下 複製代碼

<?php
function Notice(){
    include './include/conn.php';  //資料庫連結檔案
    $sql_notice = mysql_query('SELECT * FROM gg_notice where enable = "1" limit 0,10');
    $notice = mysql_fetch_array($sql_notice, MYSQL_ASSOC);
    $str = json_encode($notice);
    //linux
    return preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", $str);
    //windows
    //return preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2LE', 'UTF-8', pack('H4', '\\1'))", $str);
   
}
?>

好了其實主要是編碼問題了,解決了中文問題也就不會出現中文null或Null 字元問題了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.