jQuery中封裝了很不錯的ajax方法用來和後端交互數據。
其格式以下:ajax
$.ajax({ 請求地址 url:'www.zhouxiaohouer.com/api/user', 請求方式 type:'get', 發送給後端的數據對象 data:{ name:'zhouxiaohouer', sex:'male' } 預期服務器返回的數據類型,若是不指定,jQuery會根據響應包自動判斷,通常咱們直接設定爲json dataType:'json', 成功時候的回調,參數是返回的數據 success:function(res) { console.log(res.data) }, 失敗時回調,參數是一個xhr對象 error:function(err) { console.log(err.status) } })
後端代碼:express
// 這裏以express某個路由文件說明問題,一級路由是/api var express = require('express'); var router = express.Router(); router.get('/getsth', function(req, res, next) { // 是否須要跨域 // res.header('Access-Control-Allow-Origin', '*') var name = req.query.name var price = req.query.price res.json({ status:0, msg:'success', data:{ name : name, price:price } }) // req對請求作一些事兒 // res對響應作一些事兒 // next,下一步回調事件 }); router.post('/poststh', function(req, res, next) { // 是否須要跨域 // res.header('Access-Control-Allow-Origin', '*') // post請求的參數封裝在body中,這裏在express中須要使用body-parser在路由前提早進行封裝。 var name = req.body.name var price = req.body.price res.json({ status:0, msg:'success', data:{ name : name, price:price } }) // req對請求作一些事兒 // res對響應作一些事兒 // next,下一步回調事件 }); module.exports = router;
$.ajax({ url:'www.zhouxiaohouer.com/api/getsth', type:'GET', data:{ name:'番茄炒雞蛋', price:45 }, dataType:'json', success:function(res) { console.log(res.msg) console.log(res.data) }, error:function(err) { console.log(err.status) } }) $.ajax({ url:'www.zhouxiaohouer.com/api/poststh', type:'POST', data:{ name:'農家小炒肉', price:34 }, dataType:'json', success:function(res) { console.log(res.msg) console.log(res.data) }, error:function(err) { console.log(err.status) } })