Last active
June 8, 2020 10:10
-
-
Save aa65535/8502264 to your computer and use it in GitHub Desktop.
jQuery ajax在GBK编码下的解决方案
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
// 根据当前页面编码进行URL编码 | |
$.urlEncode = function(s) { | |
var a, u; | |
a = document.createElement('a'); | |
a.href = '/?_=' + s; | |
u = a.href.slice(a.href.indexOf('/?_=') + 4); | |
return encodeURIComponent(u).replace(/%25([0-9A-F]{2})/gi, '%$1'); | |
}; | |
// 添加 localParam 方法 URL编码使用 $.urlEncode | |
$.localParam = function(a) { | |
var prefix, | |
s = [], | |
add = function(key, value) { | |
value = $.isFunction(value) ? value() : (value == null ? '' : value); | |
s[s.length] = $.urlEncode(key) + '=' + $.urlEncode(value); | |
}, | |
buildParams = function(prefix, obj) { | |
var name; | |
if ($.isArray(obj)) { | |
$.each(obj, function(i, v) { | |
buildParams(prefix + '[' + (typeof v === 'object' ? i : '') + ']', v); | |
}); | |
} else if ($.type(obj) === 'object') { | |
for (name in obj) { | |
buildParams(prefix + '[' + name + ']', obj[name]); | |
} | |
} else { | |
add(prefix, obj); | |
} | |
}; | |
if ($.isArray(a) || (a.jquery && !$.isPlainObject(a))) { | |
$.each(a, function() { | |
add(this.name, this.value); | |
}); | |
} else { | |
for (prefix in a) { | |
buildParams(prefix, a[prefix], add); | |
} | |
} | |
return s.join('&').replace(/%20/g, '+'); | |
}; | |
} (jQuery)); | |
$.ajax({ | |
type: 'POST', | |
url: '/path/ajax.php', | |
dataType: dataType, | |
data: $.localParam(data), | |
}); | |
$.post('/path/ajax.php', $.localParam(data), function (s) { | |
// do something | |
}); | |
$(selector).load('/path/ajax.php #selector', $.localParam(data), function (s) { | |
// do something | |
}); | |
$.localParam($(selector).serializeArray()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment