###以x-www-form-urlencoded方式傳值。 前端: 1,在表單提交的時候放上監聽,阻止表單的默認事件 2,將表單內容序列化 3,利用ajax提交序列化後的表單,注意在頭部請求中設置編碼格式html
前端表單代碼:前端
<form id="form1" > <input type="text" name="apple" id="apple"> <input type="text" name="apple2" id="apple2"> <button type="submit">submit</button> </form>
前端js代碼ajax
window.onload = function () { var form1 = document.getElementById("form1"); form1.addEventListener("submit",function (event) { //兩個參數:事件名稱,回調函數。 event.preventDefault(); //阻止表單的默認事件 sendMessage(); }); function sendMessage() { var xhr = new XMLHttpRequest(); //新建XMLHttpRequest對象 xhr.onreadystatechange = function () { if(xhr.readyState === 4){ if((xhr.status>=200&&xhr.status<300)||xhr===304){ alert(xhr.responseText); } else { alert("error"); } } }; xhr.open("post","testPost",true);//接受三個參數:提交方式,後臺路由,是否異步 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //用x-www-form-urlencoded方式傳值時須要發送頭部請求. xhr.send(serialize(form1)); } }; function serialize(form) { //將表單內容序列化 var parts = [], field = null, i, len; for(i=0,len=form.elements.length;i<len;i++){//遍歷表單元素,將鍵,值分別編碼,再用&鏈接。 field = form.elements[i]; if(field.name.length){ parts.push(encodeURIComponent(field.name)+"="+encodeURIComponent(field.value)); } } return parts.join("&"); }
###以x-www-form-urlencoded方式傳值。express
前端js代碼:json
window.onload = function () { var form1 = document.getElementById("form1"); form1.addEventListener("submit",function (event) { event.preventDefault(); sendMessage(); }); function sendMessage() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if(xhr.readyState === 4){ if((xhr.status>=200&&xhr.status<300)||xhr===304){ alert(xhr.responseText); } else { alert("error"); } } }; xhr.open("post","testPost",true); var formData = new FormData(form1);//不須要頭部請求,可是要新建FormData對象 formData.append("apple3","apple3");//向formData中新加入一條鍵值對. xhr.send(formData); } }
後臺代碼app
'use strict'; const express =require('express'); const orm=require('orm'); const app = express(); var bodyParser = require('body-parser'); //注意:用urlencoded方法傳值時要引用body-parser包 app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); //分別支持urlencoded與json // var multer = require('multer'); //用formdata傳值時要引用multer包。 // var upload = multer(); app.use(express.static('public')); app.get('/',function (req,res) { res.sendFile(__dirname+"/public/html/test.html") //__dirname表示項目根目錄 }); app.post('/testPost',function (req,res) { //formData傳值這樣寫'/testPost',upload.single(),function var parts = new Object(); parts.apple = req.body.apple;//接受鍵名爲apple的值 parts.apple2 = req.body.apple2; var sendMessage = JSON.stringify(parts); res.send(sendMessage); }); app.listen(3000,function () { console.log("This"); });