seamong 6 ani în urmă
părinte
comite
fa63e5e5e0
1 a modificat fișierele cu 72 adăugiri și 0 ștergeri
  1. 72 0
      docs/JavaScript/2018_10_29_02.md

+ 72 - 0
docs/JavaScript/2018_10_29_02.md

@@ -288,6 +288,78 @@ xhr.setRequestHeader('MyHeader', 'MyValue');
 xhr.send(null);
 ```
 
+### GET 请求
+
+```js
+// 语法
+xhr.open('get', 'example.php?name1=value1&name2=value2', true);
+// 向现有URL的末尾添加查询字符串参数
+function addURLParam(url, name, value) {
+  url += url.indexOf('?') == -1 ? '?' : '&';
+  url += encodeURIComponent(name) + '=' + encodeURIComponent(value);
+  return url;
+}
+// 使用
+var url = 'example.php';
+//添加参数
+url = addURLParam(url, 'name', 'Nicholas');
+url = addURLParam(url, 'book', 'Professional	JavaScript');
+//初始化请求
+xhr.open('get', url, false);
+```
+
+### POST 请求
+
+```js
+// 语法
+xhr.open('post', 'example.php', true);
+// 数据序列化,并提交
+function submitData() {
+  var xhr = createXHR();
+  xhr.onreadystatechange = function() {
+    if (xhr.readyState == 4) {
+      if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
+        alert(xhr.responseText);
+      } else {
+        alert('Request	was	unsuccessful:	' + xhr.status);
+      }
+    }
+  };
+  xhr.open('post', 'postexample.php', true);
+  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
+  var form = document.getElementById('user-info');
+  xhr.send(serialize(form));
+}
+```
+
+### FormData
+
+```js
+// 创建`FormData`并添加数据
+var data = new FormData();
+data.append('name', 'Nicholas');
+// 使用
+var xhr = createXHR();
+xhr.onreadystatechange = function() {
+  if (xhr.readyState == 4) {
+    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
+      alert(xhr.responseText);
+    } else {
+      alert('Request	was	unsuccessful:	' + xhr.status);
+    }
+  }
+};
+xhr.open('post', 'postexample.php', true);
+var form = document.getElementById('user-info');
+xhr.send(new FormData(form));
+```
+
+#### 超时设定
+
+```js
+xhr.timeout = 1000; //将超时设置为1秒钟(仅适用于IE8+)
+```
+
 ### es5 示例代码
 
 #### 跨域