关于ajax:使用Ajaxjs实现在指定位置插入html

1、写一个标签,在标签内增加上id属性。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--在script中引入jQuery,不然不会失效的-->
    <script type="text/javascript" src="/webjars/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>
    <div>
        <table align="center" border="1" cellspacing="0">
            <!--比方在这个tr标签后插入HTML-->
            <tr id="admin">
                <td>用户名</td>
                <td>受权门控</td>
                <td>门控所在场景</td>
                <td>勾销受权</td>
            </tr>
        </table>
    </div>
</body>
</html>

2、应用Ajax向服务器发动申请,

 const xml = new XMLHttpRequest();
 xml.onload = function(){
            
 }
 xml.open("GET","http://localhost:8080/page/all");
 xml.send();

3、controller层向数据库发动查问申请,将查问到的记录的汇合转化为json格局,响应给浏览器。

@RestController
@RequestMapping("/page")
public class page {
    @Autowired
    SqlDatabaseDoorImpl sqlDatabaseDoor;

    @RequestMapping("/all")
    public String methodD0orAll() throws JsonProcessingException {
        //Door类是一个pojo类,这是一个应用Spring封装MyBatis框架的查询数据库的操作
        List<Door> door = sqlDatabaseDoor.selectAllNOParam();
        System.out.println(door);
        //将查问到的汇合转化为json格局
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(door);
        System.out.println(json);
        return json;
    }
}

4、应用Ajax的回调函数,将数据库中读取到的数据展现在页面上

<script>
 const xml = new XMLHttpRequest();
        xml.onload = function(){
            if(xml.readyState==4&&xml.status==200){
                //获取响应的数据
                let vals = xml.responseText;
                console.log(vals);
                //将传入的字符串当做 JavaScript 代码进行执行
                let jsonArr = eval(vals);
                console.log(jsonArr);
                let temp = '';
                let div = document.querySelector("#admin")//获取id为admin的标签
                console.log(div)
                for(let user of jsonArr){
                    console.log(user);
                    temp =
                            '<td>'+user.dr_userName+'</td>'+
                            '<td>'+user.dr_topic+'</td>'+
                            '<td>'+user.dr_scene+'</td>'+
                            '<td><a href="#" data-name='+user.dr_userName+' data-topic='+user.dr_topic+' onclick="del()">勾销</a></td>'
                    console.log("temp="+temp);
                    //afterend 将代码插入在id为admin的标签的下一处中央
                    //beforebegin 将代码插入在id为admin的标签的上一处中央
                    //afterbegin 将代码插入在id为admin的标签内的第一个地位
                    //beforeend 将代码插入在id为admin的标签内的最初一个地位
                    div.insertAdjacentHTML("afterend",temp);
                }
            }
        }
        xml.open("GET","http://localhost:8080/page/all");
        xml.send();
</script>

能够看到,在指定的地位上曾经呈现了咱们后续插入的html。如果此时数据库中再插入一条数据。

能够看到页面上就会持续插入html

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理