使用ajax取值(第二篇)

本文详细探讨了在前端开发中使用Ajax技术从服务器获取数据的实践方法,涵盖了请求的构造、响应处理以及与Java后端的交互。通过实例解析,帮助开发者提升Ajax取值的技能,实现更高效的数据交互。

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<input type="button" id="btn" value="获取数据"/>
<table width="80%" align="center">
    <thead>
    <tr>
        <td>姓名</td>
        <td>年龄</td>
        <td>性别</td>
    </tr>
    </thead>
    <tbody id="content">
    </tbody>
</table>

<script src="jquery-3.6.0.js"></script>
<script>
    $(function () {
        $("#btn").click(function () {
            $.post("http://localhost/ajax3/a", function (data) {//url+回调函数
                console.log(data);
                let html = "";
                for (let i = 0; i < data.length; i++) {
                    html += "<tr>" +
                        "<td>" + data[i].name + "</td>" +
                        "<td>" + data[i].age + "</td>" +
                        "<td>" + data[i].sex + "</td>" +
                        "</tr>"
                }
                $("#content").html(html);

            })
        })
    })
   // http://localhost/index3.html
</script>
</body>
</html>
package com.example.controller;

import com.example.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/ajax3")
public class AjaxController3 {

    @RequestMapping("/a")
    public List<User> ajax(){
        List<User> list = new ArrayList<>();
        User user = new User("wakeup", 1, "男");
        for (int i = 0; i < 10; i++) {
            list.add(user);
        }

        return list;

    }
}

package com.example.pojo;

public class User {
    private String name;
    private int age;
    private String sex;

    public User() {
    }

    public User(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值