博客
关于我
夜光带你走进 Ajax(三)
阅读量:281 次
发布时间:2019-03-01

本文共 1536 字,大约阅读时间需要 5 分钟。

夜光序言:

 

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

 

正文: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>

转载地址:http://htbo.baihongyu.com/

你可能感兴趣的文章
MySQL Error Handling in Stored Procedures---转载
查看>>
MVC 区域功能
查看>>
MySQL FEDERATED 提示
查看>>
mysql generic安装_MySQL 5.6 Generic Binary安装与配置_MySQL
查看>>
Mysql group by
查看>>
MySQL I 有福啦,窗口函数大大提高了取数的效率!
查看>>
mysql id自动增长 初始值 Mysql重置auto_increment初始值
查看>>
MySQL in 太多过慢的 3 种解决方案
查看>>
MySQL InnoDB 三大文件日志,看完秒懂
查看>>
Mysql InnoDB 数据更新导致锁表
查看>>
Mysql Innodb 锁机制
查看>>
MySQL InnoDB中意向锁的作用及原理探
查看>>
MySQL InnoDB事务隔离级别与锁机制深入解析
查看>>
Mysql InnoDB存储引擎 —— 数据页
查看>>
Mysql InnoDB存储引擎中的checkpoint技术
查看>>
Mysql InnoDB存储引擎中缓冲池Buffer Pool、Redo Log、Bin Log、Undo Log、Channge Buffer
查看>>
MySQL InnoDB引擎的锁机制详解
查看>>
Mysql INNODB引擎行锁的3种算法 Record Lock Next-Key Lock Grap Lock
查看>>
mysql InnoDB数据存储引擎 的B+树索引原理
查看>>
mysql innodb通过使用mvcc来实现可重复读
查看>>