jQuery中封装了很不错的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某个路由文件说明问题,一级路由是/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) ???}})
数据交互 jQuery ajax
原文地址:http://www.cnblogs.com/zhouxiaohouer/p/8028457.html