XMLHttpRequest 对象用于和服务器交换数据。
向服务器发送请求
如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:
xmlhttp.open("GET","test1.txt",true); xmlhttp.send();
方法 | 描述 |
---|---|
open(method,url,async) | 规定请求的类型、URL 以及是否异步处理请求。
|
send(string) | 将请求发送到服务器。
|
GET 还是 POST?
与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。
然而,在以下情况中,请使用 POST 请求:
- 无法使用缓存文件(更新服务器上的文件或数据库)
- 向服务器发送大量数据(POST 没有数据量限制)
- 发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠
POST 请求
xmlhttp.open("POST","demo_post.asp",true); xmlhttp.send();
GET 请求
xmlhttp.open("GET","demo_get.asp",true); xmlhttp.send();
如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:
xmlhttp.open("POST","ajax_test.asp",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("fname=Bill&lname=Gates");
方法 | 描述 |
---|---|
setRequestHeader(header,value) | 向请求添加 HTTP 头。
|
但使用post方法传数据时会报如下错误:

原因是使用chrome浏览器:chrome是按照w3c标准来执行的,你可以看这里的原文描述,http://www.w3.org/TR/XMLHttpRequest/#...
Terminate these steps if header is a case-insensitive match for one of the following headers:
Accept-Charset
Accept-Encoding
Connection
Content-Length
Cookie
Cookie2
Content-Transfer-Encoding
Date
Expect
Host
Keep-Alive
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via
本人是通过chrom浏览器进行D3的绘图,所以只能取个折中的办法,采用get方法访问后台数据,效果如下:
![]()