jQuery加载方法字符集

jQuery load method charset

本文关键字:字符集 方法 加载 jQuery      更新时间:2023-09-26

我在jQuery中使用.load()方法,但我已经意识到对服务器的请求应该使用ISO-8859-1字符集,而不是UTF-8。问题是我找不到如何将加载方法设置为使用不同的编码。我读到了。ajax方法有"内容类型"设置来实现这一点,但load方法呢?当我需要在不刷新页面的情况下更新某些div的数据时,我发现load非常有用。

任何帮助都将不胜感激,谢谢。

使用ajaxSetup可以指定新ajax调用的设置。

所有使用任何函数的后续Ajax调用都将使用设置,除非被单个调用覆盖,直到下一个调用$.ajaxSetup().

使用beforeSend,您可以提供一个回调函数,在发送XMLHttpRequest对象之前对其进行修改jQuery参考

Mozilla提供有关overrideMimeType():的文档

覆盖服务器返回的MIME类型。这可以用于例如,强制将流作为text/xml进行处理和解析,甚至如果服务器没有这样报告它。必须调用此方法在send()之前。

借用这个答案的代码你可以做:

$.ajaxSetup({
    'beforeSend' : function(xhr) {
        xhr.overrideMimeType('text/html; charset=ISO-8859-1');
    },
});
//$('body').append('<div id=qqq>dfsdfsdf</div>')
//$('#qqq').load2('/index.php?showtopic=925 #post-29397','','','text/html; charset=utf-8')
//$('#qqq').load2('/index.php?showtopic=925 #post-29397','','','text/plain; charset=windows-1251')
//

jQuery.fn.load2 = function( url, params, callback, overrideMimeTypeVar) {
    if ( typeof url !== "string" && _load ) {
        return _load.apply( this, arguments );
    }
    var selector, type, response,
        self = this,
        off = url.indexOf(" ");
    if ( off >= 0 ) {
        selector = jQuery.trim( url.slice( off ) );
        url = url.slice( 0, off );
    }
    // If it's a function
    if ( jQuery.isFunction( params ) ) {
        // We assume that it's the callback
        callback = params;
        params = undefined;
    // Otherwise, build a param string
    } else if ( params && typeof params === "object" ) {
        type = "POST";
    }
    // If we have elements to modify, make the request
    if ( self.length > 0 ) {
        jQuery.ajax({
            url: url,
            // if "type" variable is undefined, then "GET" method will be used
            type: type,
            dataType: "html",
            data: params,
            // ++++++++++++++++++++++++++++++++++++++++++++++++++
            beforeSend: function(x) {
                if(x && x.overrideMimeType && overrideMimeTypeVar!=''){
                    x.overrideMimeType(overrideMimeTypeVar);
                    }}
            // +++++++++++++++++++++++++++++++++++++++++++++++++++      
        }).done(function( responseText ) {
            // Save response for use in complete callback
            response = arguments;
            self.html( selector ?
                // If a selector was specified, locate the right elements in a dummy div
                // Exclude scripts to avoid IE 'Permission Denied' errors
                jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
                // Otherwise use the full result
                responseText );
        }).complete( callback && function( jqXHR, status ) {
            self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
        });
    }
    return this;
};