小程序:ajax(頁面跳轉方式、http、ajax的應用)


1、頁面跳轉方式

概念:超鏈接標簽的作用是從一個頁面跳轉到另一個頁面,a是anchor的縮寫,意為:錨。在本網站內的頁面稱為內部鏈接

外部鏈接屬性:

href:必須要寫的屬性,用於指定鏈接目標的地址

target:用於指定鏈接頁面的打開方式,_self是默認值,_blank為在新窗口中打開

在當前窗口打開:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <h4>外部鏈接</h4>
        <a href="https://www.baidu.com/" target="_self">百度</a>
    </body>
</html>

通過外部鏈接,鏈接到百度首頁:

點擊鏈接之后,百度首頁在當前窗口打開:

 

在新窗口打開:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <h4>外部鏈接</h4>
        <a href="https://www.baidu.com/" target="_blank">百度</a>
    </body>
</html>

 點擊超鏈接之后,頁面在新的窗口打開:

默認是在當前窗口打開。

 

(2)提交表單實現頁面跳轉

定義收集用戶信息的表單:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <form action="login.html">
            <input type="text" name="username" />
            <input type="submit" />
        </form>
    </body>
</html>

定義接收數據的頁面:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <h5>你好</h5>
    </body>
</html>

點擊提交后,跳轉到第二個頁面:

 

 

 進入第二個頁面:

 

 

 

(3)js方式

頁面一:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
      <script>
           function test(){
               window.location.href='test.html';
          }    
      </script>
    </head>
    <body>
        <h4>頁面一</h4>
    <form action="test.html">
        <input type="text" name="username" />
        <input type="submit" value="提交" />
    </form>
    </body>
</html>

頁面二:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
       <script>
           function test(){
               javascript:history.go(-1);
          }    
      </script>
    </head>
    <body>
        <h4>頁面二</h4>
        <button onclick="test()">返回</button>
    </body>
</html>

點擊提交:

 

 進入頁面二后,點擊返回,可以重新回到頁面一:

 

 2、ajax請求數據

(1)GET方式:

書寫頁面,向服務器發起ajax請求:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
     賬號:<input type="text" name="user" id="user">
    <br>
    密碼:<input type="password" name="password" id="password">
    <br>
    <button id="btn">登錄</button>
    <span id="sp1"></span>
    <script>
        var user=document.getElementById("user")
        var password=document.getElementById("password")
        var btn=document.getElementById("btn")
        var sp1=document.getElementById("sp1")
        btn.onclick=function(){
            var xhr=new XMLHttpRequest();
            xhr.open("get","phpinfo.php?user="+user.value+"&password="+password.value,true)
            xhr.send();
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4&&xhr.status==200)
                console.log(xhr.responseText)
                sp1.innerHTML=xhr.responseText;
            }
        }
    </script>
</body>
</html>

書寫php,模擬服務器,向html頁面返回數據。

<?php 
header("Content-type:text/html;charset=utf-8");//字符編碼設置 
$user=$_REQUEST["user"];
$password=$_REQUEST["password"];
echo "{$user},歡迎你,你的密碼是{$password}"
?>

(2)post方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
     賬號:<input type="text" name="user" id="user">
    <br>
    密碼:<input type="password" name="password" id="password">
    <br>
    <button id="btn">登錄</button>
    <span id="sp1"></span>
    <script>
        var user=document.getElementById("user")
        var password=document.getElementById("password")
        var btn=document.getElementById("btn")
        var sp1=document.getElementById("sp1")
        btn.onclick=function(){
            var xhr=new XMLHttpRequest();
            xhr.open('POST','phpinfo.php',true)
             xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.send('user='+user.value+'&password='+password.value);
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4&&xhr.status==200)
                console.log(xhr.responseText)
                sp1.innerHTML=xhr.responseText;
            }
        }
    </script>
</body>
</html>

(3)get方式與post方式的比較

不同點:

(1)get請求的參數在URL中,post請求在請求體中。用戶一般看不到請求體中的內容,post提交相對安全

(2)請求緩存:GET 會被緩存,而post不會

post不管刷新頁面多少次,都不會304狀態。而get在未改變代碼的情況下,第一次刷新為狀態碼為200,第二次刷新狀態碼變為304。

(3)get請求長度最多1024kb,post對請求數據沒有限制(瀏覽器和服務器對其有一定的限制)

(4)ajax的get方式的請求不需要設置請求頭,而post方式需要

相同點:

GET和POST本質上都是TCP連接,但是由於HTTP的規定和瀏覽器/服務器的限制,導致他們在應用過程中表現出不同。 

 

3、HTTP

(1)http響應和http請求通稱為http協議

 

 

 點擊鏈接、提交表單都會觸發http請求,這種方式會導致頁面重載,速度較慢

(2)響應行常見狀態碼

200 :請求成功。

302 :請求重定向。

當訪問網址A時,由於網址A服務器端的攔截器或者其他后端代碼處理的原因,會被重定向到網址B。

304 :請求資源沒有改變,訪問本地緩存。

沒有被修改,直接用緩存資源,可以減小開銷

 

修改后重新加載

 

403:表明請求訪問的資源被拒絕了

404 :請求資源不存在。通常是用戶路徑編寫錯誤,也可能是服務器資源已刪除。

500 :服務器內部錯誤。通常程序拋異常

 

4、ajax獲取數據庫數據

 (1)書寫頁面,通過AJAX向服務端發起POST請求,獲取服務端的數據,將其轉換為js對象后進行遍歷渲染在頁面上:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
     
</head>
<body>
    <button id="btn">獲取數據</button>
    <div id="sp1"></div>
    <script>
        var btn=document.getElementById("btn")
        var sp1=document.getElementById("sp1")
        btn.onclick=function(){
            var xhr=new XMLHttpRequest();
            xhr.open("POST",'phpinfo.php',true)
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.send();
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4&&xhr.status==200)   
                var data=JSON.parse(xhr.responseText);
                var html="";
                for(var a in data) { 
                    html+=`
                    <tr>                        
                        <td>${data[a].Id}</td>
                        <td>${data[a].sname}</td>
                        <td>${data[a].sex}</td>
                        <td>${data[a].snum}</td>
                        <td>${data[a].hobby}</td>
                    </tr>`
                  } 
                 sp1.innerHTML=html; 
            }
            
        }
    </script>
   
</body>
</html>

(2)PHP:創建並獲取數據庫連接,訪問數據庫,從數據庫獲取數據:

<?php 
header("Content-type:text/html;charset=utf-8");//字符編碼設置 
$servername = "localhost"; 
$username = "root"; 
$password = "root"; 
$dbname = "student"; 
 
$con =mysqli_connect($servername, $username, $password, $dbname); 

$sql = "SELECT * FROM t_stu"; 
$result = mysqli_query($con,$sql); 
if (!$result) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}
 
$jarr = array();
while ($rows=mysqli_fetch_array($result,MYSQL_ASSOC)){
    $count=count($rows);//不能在循環語句中,由於每次刪除 row數組長度都減小 
    for($i=0;$i<$count;$i++){ 
        unset($rows[$i]);//刪除冗余數據 
    }
    array_push($jarr,$rows);
}
echo $str=json_encode($jarr);//將數組進行json編碼
?>

(3)創建數據庫,存儲數據:

 

 (4)測試

 

 

5、圖靈機器人

(1)向接口發起ajax請求,獲取服務端的數據:

調用接口的時候,需要輸入相關的請求參數,通過查看API獲取返回的數據中的信息

其中,data里面是請求參數

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<title>   </title>

<script>
    function formatterDateTime() {
                    var date=new Date()
                    var month=date.getMonth() + 1
                  var datetime = date.getFullYear()
                                + ""// "年"
                                + (month >= 10 ? month : "0"+ month)
                                + ""// "月"
                                + (date.getDate() < 10 ? "0" + date.getDate() : date
                                        .getDate())
                                + ""
                                + (date.getHours() < 10 ? "0" + date.getHours() : date
                                        .getHours())
                                + ""
                                + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date
                                        .getMinutes())
                                + ""
                                + (date.getSeconds() < 10 ? "0" + date.getSeconds() : date
                                        .getSeconds());
                 return datetime;
    }
    
    var me=document.getElementById("me")
    function dianji() {        
    $.ajax({
        type: 'post',
        url: 'http://route.showapi.com/26-4',
        dataType: 'json',
        data: {
            "showapi_timestamp": formatterDateTime(), //注意要使用當前時間。服務器只處理時間誤差10分鍾以內的請求
            "showapi_appid": '281861', //這里需要改成自己的appid
            "showapi_sign": 'd8499e9ea1fd48469074de312a3a2ea1',  //這里需要改成自己的密鑰
            "info":me
        },
        jsonp: 'jsonpcallback',
        error: function(XmlHttpRequest, textStatus, errorThrown) {
            alert("操作失敗!");
        },
        success: function(result) {    
           alert(result.showapi_res_error)
        }
    });
}
</script>
</head>

<body>    
     <input type="text" id="me" />
     <button onclick="dianji()">提交</button>
</body>

</html>

(2)測試

 

 

6、小程序的渲染

(1)請求數據並書寫相應的函數實現頁面的切換:

Page({
  data: {
    tabList:["全部","精華","分享","問答","招聘"],
    currentIndex:0,
    lists:[]//用來存數據
  },
  tabChange(e){
    this.setData({
        currentIndex:e.currentTarget.dataset.num
    })
    console.log(this.data.currentIndex)
    if(this.data.currentIndex==0){
      this.getLists("all");
    }else if(this.data.currentIndex==1){
      this.getLists("good");
    }else if(this.data.currentIndex==2){
      this.getLists("share");
    }else if(this.data.currentIndex==3){
      this.getLists("ask");
    }else{
      this.getLists("job");
    }
    
  },
  //獲取后台數據
  getLists(e){
    var that = this
    console.log(e)
    wx.showLoading({
      title: '正在加載中',
    })
    wx.request({
      url:"https://cnodejs.org/api/v1/topics",
      data:{
        tab:e
      },
      method:"GET",
      success:function(res){
        console.log(that)
        that.setData({
          lists:res.data.data
        })
        // ,function(){
          wx.hideLoading({})
        // }
        console.log(that.data.lists)
      },
      fail:function(error){
        console.log(error)
      }
    })
  },
  //事件處理函數
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    this.getLists("all");
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})

(2)樣式:布局頁面

/**index.wxss**/
.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.userinfo-avatar {
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  border-radius: 50%;
}

.userinfo-nickname {
  color: #aaa;
}

.usermotto {
  margin-top: 200px;
}

.tab{
  font-size: 32rpx ;
  color:#86C811 ;
}
.current{
  color:#fff;
  background-color:#86C811;
  padding:6rpx 8rpx;
}
.main{
  width:95%;
  background-color:■#ffffff;
  margin:40rpx auto;
  border-radius:6rpx 6rpx 0 0;
  font-size:28rpx;
}
.header{
  width:100%;
  height:120rpx;
  background-color:#DDDDDD;
  display:flex;
  align-items:center;
  justify-content:space-around;
  font-size:32rpx;
}
.content{
  border-radius: 0 0 6rpx 6rpx;
  background-color: #ffffff;
}

.topic_list{
  width: 100%;
  height:100rpx;
  border-radius: 1px solid #DDDDDD;
  color: #888;
  padding: 20rpx;
  box-sizing: border-box;
  position: relative;
}
.topic_list image{
  width: 60rpx;
  height: 60rpx;
  vertical-align: middle;
  
}
.put-top{
  font-size: 24rpx;
  color: #fff;
  background-color: #86c011;
  padding: 6rpx;
  border-radius: 4rpx;
  margin: 0 20rpx 0 10rpx;
  
}

.titles{
  font-size: 28rpx;
  display: inline-block;
  width: 450rpx;
  height: 50rpx;
  vertical-align: middle;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
 
}
.topic_list_bottom{
  font-size: 24rpx;
  color: #b4b4b4;
}
.reply_count{
  position: absolute;
  left: 165rpx;
  bottom: 5rpx;
}
.last_active_time{
  position: absolute;
  right: 165rpx;
  bottom: 5rpx;
}

(3)獲取數據渲染頁面

<view class="main">
  <view class="header">
    <block wx:for="{{tabList}}" >
        <view class="tab {{currentIndex==index?'current':''}}" bindtap="tabChange" data-num="{{index}}">
{{item}}</view>
      </block>
  </view>
  <view class="content">
    <navigator class="topic_list" wx:for="{{lists}}" wx:key="index">
      <view class="topic_list_bottom">
        <image src="{{item.author.avatar_url}}"></image>
        <text class="put-top" wx:if="{{item.top}}">置頂</text>
        <text class="put-top" wx:else>{{
            item.tab=="share"?"分享":item.tab=="good"?"精華":item.tab=="ask"?"問答":"招聘"}}</text>
        <text class="titles">{{item.title}}</text>
      </view>
      <view class="topic_list_bottom">
        <view class="reply_count">
          <text>{{item.reply_count}}</text>
          <text>/</text>
          <text>{{item.visit_count}}</text>
        </view>
        <text class="last_active_time">10天前</text>
      </view>

    </navigator>
  </view>
</view>

(4)測試:

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM