Ajax進階

內容:javascript

1.FormDatahtml

2.cors前端

3.Ajax對象的uploadjava

 

Ajax基礎:http://www.javashuo.com/article/p-phjoqrdl-cd.htmlexpress

 

 

 

1.FormData後端

(1)什麼是FormDataapi

FormData 對象的使用:跨域

  • 用一些鍵值對來模擬一系列表單控件:把form中全部表單元素的name與value組裝成一個queryString
  • 異步上傳二進制文件

FormData主要用於上傳文件瀏覽器

建立FormData對象:服務器

1 let formData = new FormData()

 

(2)FormData的方法

1 set(key, value)              會覆蓋
2 append(key, value)        不覆蓋
3 get(key)
4 getAll(key)
5 delete(key)
6 forEach

 

 方法使用實例:

1 let data=new FormData()
2 data.set('user', 'wyb')
3 console.log(data.get('user'))       // wyb
4 data.append('user', 'wyb_test')
5 console.log(data.getAll('user'))    // ["wyb", "wyb_test"]

 

(3)FormData使用實例

 1 <!-- author: wyb -->
 2 <!DOCTYPE html>
 3 <html lang="en">
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1">
 7     <title>登錄頁面</title>
 8     <script>
 9         let $ = function (sel) {
10             return document.querySelector(sel)
11         }
12 
13         window.onload = function () {
14             let oUser = $('#user')
15             let oPass = $('#pass')
16             let oBtn = $('#btn1')
17 
18             oBtn.onclick = function () {
19                 let data = new FormData
20                 data.set("user", oUser.value)
21                 data.set("pass", oPass.value)
22 
23                 // Ajax:
24                 let oAjax = new XMLHttpRequest()
25 
26                 // GET
27                 /*
28                     let arr = []
29                     data.forEach(function (value, key) {
30                         // console.log(key, value)
31                         arr.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
32                     })
33                     oAjax.open('GET', `http://localhost:8080/api?${arr.join("&")}`, true)
34                     oAjax.send()
35                 */
36 
37                 // POST
38                 oAjax.open('GET', 'http://localhost:8080/api', true)
39                 oAjax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
40                 oAjax.send(data)
41 
42                 oAjax.onreadystatechange = function () {
43                     if(oAjax.readyState === 4){
44                         if(oAjax>=200 && oAjax.status<300 || oAjax.status === 304){
45                             alert('成功')
46                         } else{
47                             alert('失敗')
48                         }
49                     }
50                 }
51 
52             }
53             
54         }
55 
56     </script>
57 </head>
58 <body>
59 
60 <input type="text" id="user">
61 <input type="password" id="pass">
62 <input type="button" value="提交" id="btn1">
63 
64 </body>
65 </html>

 

(4)FormData上傳文件實例

前端:

 1 <!-- author: wyb -->
 2 <!DOCTYPE html>
 3 <html lang="en">
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1">
 7     <title>上傳文件</title>
 8     <script>
 9         let $ = function (sel) {
10             return document.querySelector(sel)
11         }
12 
13         window.onload = function () {
14             let oFile = $('#f1')
15             let oBtn = $('#btn1')
16 
17             oBtn.onclick = function () {
18                 let data = new FormData()
19                 // 拼接文件數據
20                 Array.from(oFile.files).forEach(function (file) {
21                     data.append("f1", file)
22                 })
23 
24                 // Ajax:
25                 let oAjax = new XMLHttpRequest()
26 
27                 // POST
28                 oAjax.open('POST', 'http://localhost:8080/api', true)
29                 oAjax.send(data)
30 
31                 oAjax.onreadystatechange = function () {
32                     if(oAjax.readyState === 4){
33                         if(oAjax>=200 && oAjax.status<300 || oAjax.status === 304){
34                             alert('成功')
35                         } else{
36                             alert('失敗')
37                         }
38                     }
39                 }
40 
41             }
42             
43         }
44 
45     </script>
46 </head>
47 <body>
48 
49 <!-- 能夠同時上傳多個文件 -->
50 上傳文件: <input type="file" id="f1" multiple>
51 <input type="button" value="提交" id="btn1">
52 
53 </body>
54 </html>

 

後端(express):

 1 const express = require('express')          // express主體
 2 const body = require('body-parser')         // 接收普通POST數據
 3 const multer = require('multer')            // 接收文件POST數據
 4 
 5 // create server:
 6 let server = express()
 7 server.listen(8080)
 8 
 9 // 中間件:
10 server.use(body.urlencoded({extended: false}))
11 let multerObj = multer({dest: './upload/'})
12 server.use(multerObj.any())
13 
14 // 處理請求: -> RESTful風格
15 server.post('/api', function (req, res) {
16     if(req.headers['origin']==='null' || req.headers['origin'].startsWith('http://localhost')){
17         res.setHeader('Access-Control-Allow-Origin', '*');
18     }
19 
20     res.send("test get")
21 
22     console.log(req.body);      // 普通POST數據
23     console.log(req.files);     // 文件POST數據
24 })
25 
26 // 設置靜態文件路徑
27 server.use(express.static('./www/'))

啓動服務端後在瀏覽器輸入http://localhost:8080/xxx.html便可訪問存儲在www文件夾下的文件,而後在此頁面中上傳文件

 

 

2.cors

(1)什麼是跨域

跨域解釋:瀏覽器對於javascript的同源策略的限制,例如a.cn下面的js不能調用b.cn中的js,對象或數據(由於a.cn和b.cn是不一樣域),因此跨域就出現了

同源策略:請求的url地址,必須與瀏覽器上的url地址處於同域上,也就是域名,端口,協議相同

跨域:在網絡中不存在跨域這回事兒——跨域只是瀏覽器對咱們的限制

想實現跨域就要在服務器端進行設置,設置Access-Control-Allow-Origin

 

(2)Access-Control-Allow-Origin

使用方法:Access-Control-Allow-Origin: 域名||*

注:指定某個域名後就能夠容許這個經過這個域名來訪問,指定*表示容許一切的訪問

  • Server:驗證headers['origin']認不認識,若是認識=>setHeader('Access-Control-Allow-Origin', '*')
  • Client:不須要作任何事

 

 

3.Ajax對象的upload

(1)使用方法

 1 oAjax.upload.onprogress=function (ev){  // oAjax是Ajax對象
 2   ev.loaded       完成
 3   ev.total        總共
 4 
 5   ev.loaded/ev.total      =>0~1
 6 };
 7 
 8 // 注意:
 9 1.upload必須放在Ajax對象建立以後、send以前
10 2.之前的上傳——POST
11   加了upload——OPTIONS、POST
12 3.服務器必須能處理OPTIONS
13   通用服務器——不用擔憂
14   NodeJS服務——use
15 4.oAjax.onprogress            下載進度
16 oAjax.upload.onprogress     上傳進度

 

(2)用upload實現上傳進度實例

HTML: 

 1 <!-- 能夠同時上傳多個文件 -->
 2 <div>
 3     上傳文件: <input type="file" id="f1" multiple>
 4     <input type="button" value="提交" id="btn1">
 5 </div>
 6 <!--上傳進度: <meter id="m1" value="" min="0" max="100" style="width: 500px;"></meter>-->
 7 上傳進度:
 8 <div class="parent">
 9     <div class="child">
10 
11     </div>
12 </div>

CSS:

 1 .parent {
 2     width: 500px;
 3     height: 20px;
 4     border: 1px solid black;
 5 }
 6 
 7 .child {
 8     width: 0;
 9     height: 100%;
10     background: green;
11 }

JavaScript:

 1 let $ = function (sel) {
 2     return document.querySelector(sel)
 3 }
 4 
 5 window.onload = function () {
 6     let oFile = $('#f1')
 7     let oBtn = $('#btn1')
 8 
 9     oBtn.onclick = function () {
10         let data = new FormData()
11         // 拼接文件數據
12         Array.from(oFile.files).forEach(function (file) {
13             data.append("f1", file)
14         })
15 
16         // Ajax:
17         let oAjax = new XMLHttpRequest()
18 
19         oAjax.upload.addEventListener('progress', function (ev) {
20             alert('progress')
21             console.log(ev)
22 
23             // 計算進度
24             let v = 100 * ev.loaded / ev.total + '%'
25             let oChild = document.getElementsByClassName('child')[0];
26 
27             // 設置進度
28             oChild.style.width = v;
29         }, false);
30 
31         // POST
32         oAjax.open('POST', 'http://localhost:8080/api', true)
33         oAjax.send(data)
34     }
35 }
相關文章
相關標籤/搜索