我正在使用 JQuery load() 方法将内容加载到页面。唯一的问题是,当通过 load() 方法加载内容时,所有国家(波兰语)字符都显示无效......在加载和主要(加载内容)的页面上,编码设置为 iso-8859-2(是,我知道,我应该使用 utf-8 bo 它在这种情况下没有帮助)。
我真的不知道如何解决它。我想到的唯一解决方案是在加载之前和接收数据解码之后用一些代码替换特殊字符,但这有点复杂:D
有任何想法吗?
干杯
好的,我做了一些研究。这就是我发现的:
jQuery.load()
不会meta
查看content-type
. 您可以选择以下两个选项之一:
要将 HTTP 响应标头设置为Content-type: text/html; charset=iso-8859-2
然后使用 jQuery .load()
。例如,在 PHP 中,您可以通过将其放在页面顶部来做到这一点:
<?php header('Content-type: text/html; charset=iso-8859-2'); ?>
使用 jQuery 在客户端覆盖 HTTP 响应内容类型。为此,您应该将设置传递mimeType: "text/html; charset=iso-8859-2"
给$.ajax()
. 您不能这样做,.load()
因为它不支持设置 ajax 设置的能力。
两个选项都经过测试,所以一切都应该工作!:)
假设您选择的字符集(ISO-8859-2)实际上可以表示您要使用的字符,听起来好像服务器没有使用正确的字符集('charset')提供文件存在问题。
如果您load()
用于请求 HTML 文件,则 HTML 文件的 charset 参数可以由Content-Type
响应中的标头设置,也可以作为meta
标记包含在 HTML 内容中。
设置 Content-Type 标头的具体方式取决于您生成或提供 HTML 的方式。W3C 有一个很好的文档,描述了如何在几种 Web 服务器和编程语言中做到这一点:
http://www.w3.org/International/O-HTTP-charset
设置字符集元标记可能会更容易。不同版本的 HTML 之间的确切语法不同,您可以在此处找到一些信息:
正如一些评论者所建议的那样,如果您想最大限度地支持您的网站中的不同语言,那么考虑转向像 UTF-8 这样的 Unicode 编码也是一个好主意,这样可以最大限度地减少发生这些不兼容的可能性。
都是抛光的吗?如果没有,您可以为这些字符尝试 HTML 实体,浏览器将进行解码。
http://en.wikipedia.org/wiki/Polish_alphabet#Computer_encoding
我有同样的问题,我通过阅读多个线程解决了它。我所做的是创建一个新函数/插件并在其中添加 mimetype 和 contentType,它返回了正确的编码。
(function($){
$.fn.formatload = function( url, params, callback ) {
if ( typeof url !== "string" ) {
return _load.call( this, url );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf(" ");
if ( off >= 0 ) {
var selector = url.slice(off, url.length);
url = url.slice(0, off);
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = null;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
mimeType: "text/html; charset=iso-8859-2",
dataType: "html",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: params,
complete: function( res, status ) {
// If successful, inject the HTML into all the matched elements
if ( status === "success" || status === "notmodified" ) {
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div />")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(res.responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
}
if ( callback ) {
self.each( callback, [res.responseText, status, res] );
}
}
});
return this;
}
})(jQuery);
它被称为正常的 jQuery 加载。例如
$('#div').formatload(url, data, function(data){/*在这里做事 */ });