如果服务器编码为GBK,在使用jquery autocomplete插件的时候会出现乱码。
1.服务器接收autocomplete的请求中有中文出现乱码
需要在autocomplete发送请求时对请求的参数按GBK进行编码,但JS 的encodeURI 方法只能采用默认的UTF-8编码
我们借助一段VB代码进行转换:
Function URLEncoding(vstrIn)
dim i
strReturn = ""
For i = 1 To Len(vstrIn)
ThisChr = Mid(vStrIn,i,1)
If Abs(Asc(ThisChr)) &HFF and Abs(Asc(ThisChr))<>&H25 and Abs(Asc(ThisChr))<>&H26 Then
strReturn = strReturn & ThisChr
ElseIf Abs(Asc(ThisChr))=&H25 or Abs(Asc(ThisChr))=&H26 then
strReturn = strReturn & "%" & Hex(Asc(ThisChr))
Else
innerCode = Asc(ThisChr)
If innerCode 0 Then
innerCode = innerCode + &H10000
End If
Hight8 = (innerCode And &HFF00)\ &HFF
Low8 = innerCode And &HFF
strReturn = strReturn & "%" & Hex(Hight8) & "%" & Hex(Low8)
End If
Next
URLEncoding = strReturn
End Function
下载 URLEncoding.js
在调用页面可以用如下方式引入:
如何让jquery autocomplete发送时调用URLEncoding.js进行GBK编码呢?
可以修改jquery.autocomplete.js文件:
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
q: lastWord(term),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
}
});
为:
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
q: URLEncoding(lastWord(term)),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
}
});
下载修改后的autocomplete.js
2.autocomplete 接收的结果中有中文乱码
只需设置 response.setCharacterEncoding("UTF-8");即可