XMLHttpRequest 对象用于和服务器交换数据。
向服务器发送请求
如需将请求发送到服务器,可以使用 XMLHttpRequest 对象的 open() 和 send() 方法:
xhr.open("get","test1.php",true);
xhr.send();
GET 还是 POST?
与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。
然而,在以下情况中,请使用 POST 请求:
- 无法使用缓存文件(更新服务器上的文件或数据库)
- 向服务器发送大量数据(POST 没有数据量限制)
- 发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠
GET 请求
xhr.open("get","demo1.php?name=jake&age=13",true);
xhr.send(null);
POST 请求
xhr.open("post","demo2.php",true);
xhr.send();
如果需要像 HTML 表单那样 POST 数据,必须使用 setRequestHeader()
来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:
xhr.open("post","demo2.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("name=jake&age=13");
url - 服务器上的文件
open() 方法的 url 参数是服务器上文件的地址:
xhr.open("get","test1.php",true);
该文件可以是任何类型的文件,比如 .txt 和 .xml,或者服务器脚本文件,比如 .asp 和 .php (在传回响应之前,能够在服务器上执行任务)。