AJAX-get,post,ajax三种常用请求方式

如果要想详细了解ajax,点击菜鸟教程链接 http://www.runoob.com/ajax/ajax-tutorial.html,
在这我不做详细的介绍

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
</head>
<body>
         // 给三个点击事件
    <button id="myGet">get-ajax</button>
    <button id="myPost">post-ajax</button>
    <button id="myAjax">ajax</button>
</body>
//导入jquery  
<script src="jquery.js"></script>
<script>
    // get
    // 给事件一个点击事件
    $('#myGet').click(function(){
        // alert('点击了')
        // 回调函数  里面三个参数 data 是回调的数据, status状态 ,xhr 是ajax的核心 XMLHttpRequest
        $.get('/getTest',{name:'小明',age:17},function(data,status,xhr){
            console.log(data)
        })
    })

//   post请求
    $('#myPost').click(function(){
        $.post('/postTest',{name:"小王",age:16},function(data){
            console.log(data)
        })
    })

    // ajax
    $('#myAjax').click(function(){
        $.ajax({
            // 请求地址,接口
            url:'/ajaxTest',
            // 请求的参数,内容
            data:{name:'ajax',des:'这是我的第一个ajax请求'},
            // 请求的类型 默认是get 可以不写
            type:'post',
               
            // 设置超时时间
            timeout:1000*30,
            
            //  接收数据成功 data为接收的内容
            success:function(data){
                console.log('success接收成功')
                console.log('接受的内容:'+data)
            },
            // 接收数据失败
            error:function(data){
                console.log('error')
                console.log(data)
            },
            // 发送数据之前
            beforeSend:function(){
                console.log('哈哈哈要发送了')
            },
            // 发送完成
            complete:function(){
                console.log('complete'+'发送完成')
            }
        
        })
    })
</script>
</html>

后端:

//导入需要模块
var express = require('express')
var bodyParser = require('body-parser')
var web = express()
web.use(express.static('public'))
web.use(bodyParser.urlencoded({extended:false}))

// ajax  —— get方法
web.get('/getTest',function(req,res){
    var name =req.query.name
    var age = req.query.age
    res.send('发送的数据是:'+name + ',' + age)
})

// ajax —— post方法
web.post('/postTest',function(req,res){
    var name = req.body.name
    var age = req.body.age
    res.send('发送的数据是:'+name + '.' +age)
})

// ajax 方法
web.post('/ajaxTest',function(req,res){
    var des = req.body.des
    res.send('发送的数据是:'+des)
})
web.listen('8080',function(){
    console.log('服务器已经开启...')
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值