File tree Expand file tree Collapse file tree 1 file changed +10
-2
lines changed Expand file tree Collapse file tree 1 file changed +10
-2
lines changed Original file line number Diff line number Diff line change 23
23
var xhr = new XMLHttpRequest ();
24
24
```
25
25
26
- 一旦新建实例,就可以使用` open() ` 方法发出 HTTP 请求 。
26
+ 一旦新建实例,就可以使用` open() ` 方法指定建立 HTTP 连接的一些细节 。
27
27
28
28
``` javascript
29
29
xhr .open (' GET' , ' http://www.example.com/page.php' , true );
30
30
```
31
31
32
- 上面代码向指定的服务器网址,发出 GET 请求 。
32
+ 上面代码指定使用 GET 方法,跟指定的服务器网址建立连接。第三个参数 ` true ` ,表示请求是异步的 。
33
33
34
34
然后,指定回调函数,监听通信状态(` readyState ` 属性)的变化。
35
35
@@ -43,6 +43,14 @@ function handleStateChange() {
43
43
44
44
上面代码中,一旦` XMLHttpRequest ` 实例的状态发生变化,就会调用监听函数` handleStateChange `
45
45
46
+ 最后使用` send() ` 方法,实际发出请求。
47
+
48
+ ``` javascript
49
+ xhr .send (null );
50
+ ```
51
+
52
+ 上面代码中,` send() ` 的参数为` null ` ,表示发送请求的时候,不带有数据体。如果发送的是 POST 请求,这里就需要指定数据体。
53
+
46
54
一旦拿到服务器返回的数据,AJAX 不会刷新整个网页,而是只更新网页里面的相关部分,从而不打断用户正在做的事情。
47
55
48
56
注意,AJAX 只能向同源网址(协议、域名、端口都相同)发出 HTTP 请求,如果发出跨域请求,就会报错(详见《同源政策》和《CORS 通信》两章)。
You can’t perform that action at this time.
0 commit comments