分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

数据交互 jQuery ajax

发布时间:2023-09-06 01:30责任编辑:白小东关键词:jQuery

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved