jQuery发送Ajax请求

本文档通过一个简单示例介绍如何使用jQuery的Ajax方法发送请求。前端代码演示了Ajax请求的实现,服务器端脚本则接收并处理这些请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jQuery发送Ajax请求小示例

前端发送:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <h1>jquery发送ajax请求示例</h1>
    <button>get请求</button>
    <button>post请求</button>
    <button>通用请求</button>
    <script>
        $('button').eq(0).click(function(){
            //$.get('url',{参数},回调函数,响应式类型) 
            $.get('http://127.0.0.1:8000/jquery-server',{a:1,b:2},function(response){
                console.log(response);//hello jquery ajax
            },'json');//json 自动把响应结果转为json格式
        });
        $('button').eq(1).click(function(){
            $.post('http://127.0.0.1:8000/jquery-server',{a:1,b:2},function(response){
                console.log(response);//hello jquery ajax
            },'json');
        });
        $('button').eq(2).click(function(){
            $.ajax({
                //url
                url:'http://127.0.0.1:8000/jquery-server',
                //参数
                params:{a:1,b:2},
                //请求类型
                type:'get',
                //响应结果类型
                dataType:'json',
                //超时时间
                timeout:2000,
                //成功的回调
                success:function(response){
                    console.log(response);
                },
                //失败的回调
                error:function(){
                    console.log('请求出错了...');
                },
                //设置头部信息
                Headers:{
                    c:300,
                    d:400
                }
            });
        });
    </script>
</body>
</html>

服务器脚本:

const express = require('express');

const app = express();

app.all('/jquery-server',(request,response)=>{
    //允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
    //允许自定义header头部信息
    response.setHeader('Access-Control-Allow-Headers','*');
    //设置响应
    //response.send('hello jquery ajax');
    const data = {
        name:'tom',
        age:20
    }
    response.send(JSON.stringify(data));
})

app.listen(8000,()=>{
    console.log('服务器已开启...')
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值