Ajax JSON 中文亂碼 List轉JSON,JSON轉String
我在使用級聯下拉框的時候用到Ajax技術向背景請求子框的資訊。但是出現了中文亂碼的問題,我嘗試了3種方法,發現了一條做最好的解決方法。
思路:
1.在前台擷取父框的ID,通過ajax送出到背景
2.背景根據父框ID擷取子框List集合
3.将List集合轉換成JSON格式
4.将JSON格式轉換為字元串(String)格式,并輸入到response的write裡
5.在前台擷取字元串,在轉換成JSON格式,并通過js列印輸出
背景Controller
@RequestMapping("getSonBoard")
@ResponseBody
public void getSonBoard(int id, HttpServletResponse response){
//處理亂碼問題
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
List<Sonboard> sonboards=boardService.getSonBoardsByFaterBoardId(id);
//JSON包使用org.json.*;
JSONArray jsonArray=new JSONArray();
//将LIST集合轉換為json格式
for(Sonboard board:sonboards){
JSONObject object=new JSONObject();
object.put("id",board.getSonboardId());
object.put("name",board.getBoardName());
jsonArray.put(object);
}
try {
//将json的字元串形式寫進response裡
response.getWriter().print(jsonArray.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
前台
<tr>
<td style="width: 20%; height: 40px; background-color: #E5F4FB;">選擇版塊</td>
<td style="width: 80%; height: 40px;text-align:left;">
<div class="form-group">
<!-- 循環周遊下拉框 -->
<select class="form-control" id="fatherboard"
style="width:300px;float:left; ">
<option value="0" selected="selected">-選擇大闆塊-</option>
<c:forEach items="${boards}" var="board">
<option value="${board.boardId}"> ${board.boardName} </option>
</c:forEach>
</select>
<select class="form-control" id="sonboard" name="boardid" style="width:200px; float:left; ">
<option value="">-選擇小闆塊-</option>
</select>
<span style="color:red;">請選擇所要發帖的版塊</span>
</div>
</td>
</tr>
<script type="text/javascript">
$(document).ready(function() {
//change用于截獲下拉框的狀态變化
$("#fatherboard").on('change', function() {
//擷取父框的選擇值
var id = $(this).val();
$.ajax({
type : "post",
url : "getSonBoard", //需要用來處理ajax請求的action,findson為方法名,board是namespace
data : {
//設定資料源
id : $(this).val()
},
scriptCharset: 'utf-8',
success : function(data) {
//var json= JSON.stringify(data);
json = eval("(" + data + ")"); //将資料轉換成json類型,可以把data用alert()輸出出來看看到底是什麼樣的結構
//清空子下拉框
$('#sonboard').empty();
//循環變量子下拉框
for (var i = 0; i < json.length; i++) {
var s = json[i];
$('#sonboard').append("<option value=" + s.id + ">" + s.name + "</option>");
}
},
error : function(data) {
alert("系統異常,請稍後重試!"+data);
} //這裡不要加","
});
});
});
效果
