У меня есть страница JSP/Servlet с JQgrid (версия 4.1.2). В этой сетке, когда есть какой-либо символ акцента, он не отображает эти символы. Сетка получает свой вход в формате JSON.JQGrid, не отображающий символы акцента
Я проверил, что символы акцента записываются в объект ответа. Используя firebug, я увидел, что ответ JSON, полученный сеткой, не имеет символов акцента. Информация заголовка запроса
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Type text/html; charset=UTF-8
Cookie XXXX
Host XXXX
Referer http://XXXXXXXX
User-Agent Mozilla/5.0 (Windows NT 5.2; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
X-Requested-With XMLHttpRequest
И заголовок ответ
Content-Type text/html
Date Tue, 25 Nov 2014 10:42:29 GMT
Server Apache-Coyote/1.1
Transfer-Encoding chunked
Я также установить заголовок ответа в Content-Type для application/json
, но и получил строку JSON не показывает акцент характер.
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
Когда я гугл этого вопроса он упоминался использовать autoencode:true
и ajaxGridOptions: { contentType: 'text/html; charset=UTF-8' }
и formatter:null
. Также было упомянуто добавление <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
. Я также добавил <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
Но все же символы акцента не показаны. Может ли кто-нибудь дать мне знать, что мне не хватает?
тест-коды: Servlet JQGridDemo
код
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
@SuppressWarnings("serial")
public class JQGridDemo extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String action = request.getParameter("action");
String page = "1";
String totalPages = "2";
String totalCount = "15";
String[] rowId = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"11", "12", "13", "14", "15" };
String[] InvNo = { "101", "102", "103", "104", "105", "106", "107",
"108", "109", "110", "111", "112", "113", "114", "115" };
String[] DateRec = { "03/30/12", "03/31/12", "04/01/12",
"04/02/12", "04/03/12", "04/04/12", "04/05/12",
"04/06/12", "04/07/12", "04/08/12", "04/09/12",
"04/10/12", "04/11/12", "04/12/12", "04/13/12" };
String[] AmountRec = { "11000", "12000", "13000", "14000", "15000",
"16000", "17000", "18000", "19000", "20000", "21000", "22000",
"23000", "24000", "25000" };
String[] TaxRec = { "1000", "1000", "1000", "1000", "1000", "1000",
"1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000",
"1000" };
String[] TotalRec = { "12000", "13000", "14000", "15000", "16000",
"17000", "18000", "19000", "20000", "21000", "22000", "23000",
"24000", "25000", "26000" };
String[] NotesRec = { "Mineta San José", "Invoice 2", "Invoice 3",
"Invoice 4", "Mineta San José", "Invoice 6", "Invoice 7",
"Invoice 8", "Invoice 9", "Invoice 10", "Invoice 11",
"Invoice 12", "Invoice 13", "Invoice 14", "Invoice 15" };
response.setContentType("application/json; charset=UTF-8");
response.setCharacterEncoding("utf-8");
try {
if (action.equals("fetchDataJSON")){
response.setContentType("text/json; charset=UTF-8");
JSONArray cellarray = new JSONArray();
JSONObject responsedata = new JSONObject();
responsedata.put("page", page);
responsedata.put("total", totalPages);
responsedata.put("records", totalCount);
for(int record = 0; record < rowId.length; record++){
JSONArray cell = new JSONArray();
JSONObject cellobj = new JSONObject();
cellobj.put("id", record + "");
cell.add(InvNo[record]);
cell.add(DateRec[record]);
cell.add(AmountRec[record]);
cell.add(TaxRec[record]);
cell.add(TotalRec[record]);
cell.add(NotesRec[record]);
cellobj.put("cell", cell);
cellarray.add(cellobj);
/*cellobj.clear();
cell.clear();*/
}
responsedata.put("rows", cellarray);
out.write(responsedata.toString());
}
} catch (Exception e) {
e.printStackTrace();
}finally{
out.close();
}
}
// Process the doGet request
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
// Process the doPost request
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
}
Test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="application/json; charset=UTF-8">
<title>Home</title>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
url:'<%=request.getContextPath()%>/JQGridDemo?q=1&action=fetchDataJSON',
datatype: 'JSON',
autoencode:true,
mtype: 'GET',
colNames:['Inv No','Date', 'Amount','Tax','Total','Notes'],
colModel :[
{name:'invid',index:'invid',width:55,
sortable:false,editable:true,hidden:false,
editoptions: {disabled: false},
editrules:{edithidden:true,custom:false}},
{name:'invdate', index:'invdate', width:160,
sortable:false,editable:true,hidden:false,
editrules :{edithidden:false,required:false,date:true},
editoptions :{dataInit:function(element){$(element).datepicker(
{dateFormat:'mm/dd/yy'});}},
formatoptions: {newformat:'m/d/Y'},
formoptions:{elmprefix:' '}},
{name:'amount',index:'amount',width:80,align:'right',
sortable:false,editable:true,hidden:false,
editoptions: {disabled: false},
editrules:{edithidden:true,custom:false},
formoptions:{elmprefix:'*'}},
{name:'tax',index:'tax',width:80,align:'right',
sortable:false,editable:true,hidden:false,
editoptions: {disabled: false},
editrules:{edithidden:true,custom:false}},
{name:'total',index:'total',width:80,align:'right',
sortable:false,editable:true,hidden:false,
editoptions: {disabled: false},
editrules:{edithidden:true,custom:false}},
{name:'note', index:'note', width:150,
sortable:false,editable:true,hidden:false,
editoptions: {disabled: false},
editrules:{edithidden:true,custom:false},
autoencode: false}
],
pager: '#pager1',
rowNum:5,
height:'auto',
loadonce:true,
width:'100%',
gridview: true,
autowidth:true,
shrinkToFit:false,
rowList:[5,10,15,20,25,30],
sortname: 'invid',
sortorder: 'asc',
viewrecords: true,
editurl:'<%=request.getContextPath()%>/JQGridDemo?q=1&action=editDataJSON',
caption: 'My first grid',
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
});
$("#list").jqGrid('navGrid',"#pager1",{add:true,edit:true,del:true,search:true,refresh:true,
beforeRefresh: function(){
$("#list").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid', [{page:1}]);
}},
{},{},{},{
closeAfterSearch: true,
modal: true
});
});
</script>
</head>
<body>
<table id="list">
</table>
<div id="pager1"></div>
</body>
Я испытал этот код с json-lib-2.4-jdk15.jar
и json-simple.jar
библиотеки JSON. Символы акцента не показаны в JQGrid
Вы написали: «Используя firebug, я увидел, что ответ JSON, полученный сеткой, не имеет символов акцента». Таким образом, проблема, которая у вас есть, не зависит от jqGrid. Он находится в ** серверном коде **, который возвращает данные JSON. Вы должны написать более подробную информацию о коде. Он должен включать что-то вроде 'response.setContentType (« application/json »); response.setCharacterEncoding ("UTF-8"); response.getWriter(). write (pureJsonData); 'или другое зависит от технологии, используемой на сервере. – Oleg
При дальнейшем анализе firebug, который на вкладке консоли символы акцента отображаются неправильно, но на вкладке net символы отображаются правильно. Я также отлаживал код сервера и обнаружил, что до тех пор, пока данные не будут записаны в объект ответа, символы акцента отображаются правильно. Как только он отправляется в пользовательский интерфейс и принимается в пользовательском интерфейсе, символы теряются. Я также добавил 'URIEncoding =" UTF-8 "useBodyEncodingForURI =" true "' в файле tomcats server.xml. Тогда и символы не отображаются. – Natraj
Вы должны открыть HTML-страницу, содержащую jqGid, в веб-браузере и изучить ее часть заголовка.Вы должны добавить свой код с информацией, начинающейся с ''. Голова должна содержать '' или некоторая близкая строка, точный синтаксис которой зависит от ' 'который вы используете. – Oleg