页面初始化Ajax请求与document.write冲突

样例分析仅展示部分代码片段

页面初始化 加载数据库中的内容

ajax发送请求

$(function(){
        $.ajax({
            type: 'get',
            contentType: 'application/json;charset=UTF-8',
            url: '/InitializeNotes',
            dataType: 'text',
            success: function (data, status) {
                document.write(data); 
                document.close();  
            },
            error:function(status){
                alert(status);
            }
        });
});

从数据库中获取内容保存为Collection集合 

@RequestMapping(value="/InitializeNotes",method={RequestMethod.GET})
public String list(Model model){
    Collection<Note> notes = noteDao.getAll();
    model.addAttribute("notes",notes);
    return "/main";
}

 

前端页面使用thymeleaf进行解析

<tbody>
            <tr th:each="note:${notes}">
                <td th:text="${note.id}"></td>
                <td th:text="${note.content}"></td>
                <td>
                    <form th:action="@{/editNote/}+${note.id}" method="post">
                        <input type="hidden" name="edit" value="edit">
                        <button type="submit" value="编辑">编辑</button>
                    </form>
                </td>
                <td>
                    <form th:action="@{/deleteNote/}+${note.id}" method="post">
                        <input type="hidden" name="id" th:value="${note.id}">
                        <button type="submit" value="删除">删除</button>
                    </form>
                </td>
            </tr>
</tbody>

ajax请求成功 将返回的data写入(见上Ajax请求)

注意 : 返回的data 是整个html页面,已经解析渲染完成好的页面 ,在response中可以看到整个页面

使用document.write重写整个页面,但还没有结束。

 

注意: 重写完成后 需要配合使用document.close 进行结束,否则会一直等待输入。

若不使用document.close 结束的话,页面能够展示 ,但是页面中的js就失效了。

但若使用 document.close 结束写入后 页面中有ajax请求 又会重新发送一遍,然后重新写入页面,造成死循环。 

 

我想到的解决方案 自然是弃用document.write(data) 方法,取而代之的是将Ajax请求返回的数据手动修改页面。

success: function (data, status) {
                var u_content = $(data).find("#user-content").html();
                $("#user-content").html(u_content);
}

若有错误,欢迎指正。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值