html代碼
- <html>
- <head>
- <meta http-equiv="content-type" content="text/html;charset=utf-8">
- <title>js局部刷新</title>
- <style type="text/css">
- #h1{
- text-align:center;
- }
- #div{
- margin:0 auto;
- width:300px;
- height:200px;
- background:#ccc;
- }
- button{
- display:block;
- margin:0 auto;
- }
- </style>
- </head>
- <body>
- <h1 id='h1'>js局部刷新</h1>
- <div id='div'>
- </div>
- <h1 id='h1'><script>document.write(new Date())</script></h1>
- <button id="bid" name="button" onclick="fasong()">請求數據get方式</button>
- <button id="bid" name="button" onclick="fasong2()">請求數據post方式</button>
- </body>
- <script>
- //js異步請求php數據 (get方式)
- function fasong(){
- var xhr=new XMLHttpRequest();//生成XMLHttpRequest對象
- xhr.onreadystatechange=function(){
- //當readyState==4 status==200表示響應成功
- if(xhr.readyState==4 && xhr.status==200){
- //alert(xhr.responseText);
- var data=xhr.responseText;
- var divobj=document.getElementById('div')
- divobj.innerHTML=data;
- //hid.innerHTML=data;
- }
- }
- //false 爲同步
- xhr.open("get","index.php?",true);//準備好發送數據之前的準備
- xhr.send();//
- }
- //js異步請求php數據 (post方式)
- function fasong2(){
- var xhr=new XMLHttpRequest();//生成XMLHttpRequest對象
- //alert(xhr);
- /**/
- xhr.onreadystatechange=function(){
- //當readyState==4 status==200表示響應成功
- if(xhr.readyState==4 && xhr.status==200){
- //alert(xhr.responseText);
- var data=xhr.responseText;
- var divobj=document.getElementById('div')
- divobj.innerHTML=data;
- //hid.innerHTML=data;
- }
- }
- //xhr.open("get","index.php?"+str,true);
- //false 爲同步
- xhr.open("post","index.php?",true);//準備好發送數據之前的準備
- xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//模擬表單 否則無法顯示數據
- xhr.send("suername=nihao&age=30");//
- }
- </script>
- </html>
php代碼
- <?php
- echo 'JavaScript局部刷新';
- echo 'JavaScript局部刷新';
- echo 'JavaScript局部刷新';