jq的getScript函数不支持chaset?override掉!

其实我历来不用jq或者其余框架的,这两天偶然在一个小项目里面发现jq的一个小bug:getScript函数没有透传charset信息,若是试图在页面上加载一个跨编码的脚本的时候会致使编码错误。写了一个补丁函数覆盖掉原来的:

$.getScript= function(url, callback , charset){
    $.ajax({
        url: url,
        dataType: "script",
        success:callback,
        scriptCharset:charset
    })
}    

这几年代码写得不多,轻喷。这里是 demo代码 ,同时也到jq的github上提交了 一个issue

<! DOCTYPE html >
< HTML >
< HEAD >
< meta  charset ="utf-8"   />
< script  src ="http://cdn.jsdelivr.net/jquery/1.11.1/jquery.js" ></ script >

< SCRIPT  LANGUAGE ="JavaScript" >
<!--
function  log(s){
    $(
" body " )[ 0 ].innerHTML += " <p> " + s.replace( / \n / g, " <br> " ).replace( / \t / g, " &nbsp&nbsp&nbsp&nbsp " ) + " </p> " ;
}
function  testBIG5(result){
    log(
" BIG5 decode  " + (result ? " correctly " : " <font color=red>incorrectly</font> " ))
}
function  testGB(result){
    log(
" gb2312 decode  " + (result ? " correctly " : " <font color=red>incorrectly</font> " ))
}
function  testUTF8(result){
    log(
" utf-8 decode  " + (result ? " correctly " : " <font color=red>incorrectly</font> " ));
}
function  testJP(result){
    log(
" iso-2022-jp decode  " + (result ? " correctly " : " <font color=red>incorrectly</font> " ));
}
function  testKR(result){
    log(
" euc-kr decode  " + (result ? " correctly " : " <font color=red>incorrectly</font> " ));
}
$(document).ready(
function (){

    $.when(
        log(
" <i>old version of getScript:</i> " ),
        log($.getScript.toString()),
        $.getScript(
" http://stonelf.sinaapp.com/testGB.js " ),
        $.getScript(
" http://stonelf.sinaapp.com/testUTF8.js " ),
        $.getScript(
" http://stonelf.sinaapp.com/testBIG5.js " ),
        $.getScript(
" http://stonelf.sinaapp.com/testJP.js " ),
        $.getScript(
" http://stonelf.sinaapp.com/testKR.js " )
    ).then(
function (){

        $.getScript
= function (url, callback , charset){
            $.ajax({
                url: url,
                dataType: 
" script " ,
                success:callback,
                scriptCharset:charset
            })
        }    

        log(
" <hr><i>new versioni of getScript:</i> " );
        log($.getScript.toString()),
        $.getScript(
" http://stonelf.sinaapp.com/testGB.js " ,undefined, " gb2312 " );
        $.getScript(
" http://stonelf.sinaapp.com/testUTF8.js " ,undefined, " utf-8 " );
        $.getScript(
" http://stonelf.sinaapp.com/testBIG5.js " ,undefined, " big5 " );
        $.getScript(
" http://stonelf.sinaapp.com/testJP.js " ,undefined, " iso-2022-jp " );
        $.getScript(
" http://stonelf.sinaapp.com/testKR.js " ,undefined, " euc-kr " );

    })
})
// -->
</ SCRIPT >
</ HEAD >
< BODY >
</ BODY >
</ HTML >
相关文章
相关标签/搜索