文章目录

  • Ajax实现页面局部刷新
  • Ajax请求成功后页面跳转

Ajax实现页面局部刷新

这里通过点击一个按钮,然后下面产生一段文字,而整个页面不用刷新

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX</title>
    <script>
        function loadXMLDoc() {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange=function () {
                if(xhr.readyState == 4 && xhr.status == 200) {

                    //通过Ajax响应的东西异步的展示在id为hello的div中
                    document.getElementById("myDiv").innerHTML=xhr.responseText;
                }
            };
            xhr.open("POST","newPage.html",true);
            xhr.send();
        }
    </script>
</head>
<body>
    <div>我的第一个AJAX</div>
    <button type="button" onclick="loadXMLDoc()">点击</button>
    <div id="myDiv"></div>
</body>
</html>

Ajax请求成功后页面跳转

通过location.href,进行页面的跳转

<input id="title" type="text" placeholder="请输入标题">
<input id="input" type="button" value="发布">
$("#input").click(function () {
   $.post({
       url: "/editormd",
       data: {
           title: $("#title").val(),
       },
       success: function () {
           location.href="/";
       }
   });

更多推荐

Ajax请求成功后页面跳转