我正在使用 jquery $.getJSON 来检索城市列表。
一切正常,但我来自爱沙尼亚,我们使用了一些字符,如 õ、ü。ä, ö。
当我将这样的字母传递给回调函数时,我不断收到空字符串。我试过base64编码(服务器端)-解码(jquery base64插件)字符串(我认为这是一个好主意,只要我可以用php压缩页面,所以我不必担心带宽),但这样我最终得到了一些随机的中文符号。
解决此问题的最佳方法是什么。
谢谢你。
You need to utf8_encode()
your output data. There's no need to set your encoding on the client side to UTF-8 as it's already default.
<?php
if( isset( $_GET['json'] ) ) {
die( json_encode( array( 'text' => utf8_encode( 'õ, ü. ä, ö' ) ) ) );
}
include_jquery(); # this outputs jquery include
>?
<script>
$.getJSON( 'this_file.php', { 'json': 1 }, function( data ) {
console.log( 'data', data );
});
</script>
您必须确保保持一致的字符编码。您想要的爱沙尼亚字符在 utf-8 中,因此您必须$.ajax
显式使用和设置字符编码(通过 contentType)。
您可以获取生成的 ajax 并对其进行处理。
您还可以在调用 getJSON 之前使用 ajaxSetup 来设置内容类型。
http://api.jquery.com/jQuery.ajaxSetup/
这将允许您使用 getJSON
此外,这里是关于同一主题的相关 SO 帖子:How to set encoding in .getJSON JQuery
在您的 php 页面中使用 UTF-8 并作为输出编码
这看起来像一些编码/字符集问题:您确定您使用的是: