javascript本身都是unicode编码的
ajax都是utf-8编码的
1 GET
2 POST
GET是一定要进行编码的
encodeURIComponent(key)
POST 貌似不需要
ajax都是utf-8编码的
1 GET
var key = $("#key").val();
var value = $("#value").val();
var postStr = "key=" + encodeURIComponent(key) + "&value=" + encodeURIComponent(value);
var xmlhttp_request = new XMLHttpRequest();
xmlhttp_request.open('GET', '${ctx}/AjaxServlet?'+postStr, true);
//xmlhttp_request.send(postStr);
xmlhttp_request.send(null);//请求体为空
xmlhttp_request.onreadystatechange = function() {
if (xmlhttp_request.readyState == 4
&& xmlhttp_request.status == 200) {
var res = xmlhttp_request.responseText;
alert(eval("(")+res+")");
}
}
2 POST
var key = $("#key").val();
var value = $("#value").val();
var postStr = "key=" + encodeURIComponent(key) + "&value=" + encodeURIComponent(value);
var xmlhttp_request = new XMLHttpRequest();
xmlhttp_request.open('POST', '${ctx}/AjaxServlet', true);
xmlhttp_request.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlhttp_request.send(postStr);//传送请求体
xmlhttp_request.onreadystatechange = function() {
if (xmlhttp_request.readyState == 4
&& xmlhttp_request.status == 200) {
var res = xmlhttp_request.responseText;
alert(eval("(")+res+")");
}
}
GET是一定要进行编码的
encodeURIComponent(key)
POST 貌似不需要
本文详细介绍了使用JavaScript通过GET和POST方式发送AJAX请求的具体实现方法。对比了两种请求方式的区别,如GET请求需要对参数进行编码,而POST请求则直接将参数作为请求体发送。此外还展示了如何设置HTTP头部信息及处理服务器响应。
155

被折叠的 条评论
为什么被折叠?



