夜光带你走进 Ajax(三)

夜光序言:

 

只要没答应那就不算失言了

 

正文:2 AJAX第二例(发送POST请求)

2.1 发送POST请求注意事项

 

POST请求必须设置ContentType请求头的值为application/x-www.form-encoded。表单的enctype默认值就是为application/x-www.form-encoded

因为默认值就是这个,所以大家可能会忽略这个值

 

当设置了<form>的enctype=” application/x-www.form-encoded”时,等同与设置了Cotnent-Type请求头。

但在使用AJAX发送请求时,就没有默认值了,这需要我们自己来设置请求头:

xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

 

当没有设置Content-Type请求头为application/x-www-form-urlencoded时,Web容器会忽略请求体的内容。

 

所以,在使用AJAX发送POST请求时,需要设置这一请求头,然后使用send()方法来设置请求体内容。

xmlHttp.send("b=B");

 

这时Servlet就可以获取到这个参数

 

AServlet

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

System.out.println(request.getParameter("b"));

System.out.println("Genius:Hello AJAX~~");

response.getWriter().print("Hello AJAX");

}

 

ajax2.jsp

<script type="text/javascript">

function createXMLHttpRequest() {

try {

return new XMLHttpRequest();//大多数浏览器

} catch (e) {

try {

return new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

return new ActiveXObject("Microsoft.XMLHTTP");

}

}

}

 

function send() {

var xmlHttp = createXMLHttpRequest();

xmlHttp.onreadystatechange = function() {

if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {

var div = document.getElementById("div1");

div.innerHTML = xmlHttp.responseText;

}

};

xmlHttp.open("POST", "/ajaxdemo1/AServlet?a=A", true);

xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xmlHttp.send("b=B");

}

</script>

<h1>AJAX2</h1>

<button onclick="send()">夜光:测试</button>

<div id="div1"></div>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值