Json與Ajax(註冊實例)

来源:https://www.cnblogs.com/chenyingying0/archive/2020/01/04/12150227.html
-Advertisement-
Play Games

需要在伺服器上進行哈 jquery的ajax方法: // jquery請求 $.ajax({ url: "./server/slider.json", type: "post", dataType: "json", async: true, success: function(datas) { re ...


需要在伺服器上進行哈

jquery的ajax方法:

    // jquery請求
    $.ajax({
        url: "./server/slider.json",
        type: "post",
        dataType: "json",
        async: true,
        success: function(datas) {
            renderData(datas.slider);
        }
    })

    // jquery渲染數據
    function renderData(data) {
        var str = "";
        $.each(data, function(index, obj) {
            str += '<a href="' + obj.linkUrl + '"><img src="' + obj.picUrl + '"></a>'
        })
        $("#banner_jq").html(str);
}

跨域請求,封裝jsonp函數

    function getJSONP(url, callback) {
        if (!url) {
            return;
        }
        var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']; 
        //定義一個數組以便產生隨機函數名
        var r1 = Math.floor(Math.random() * 10);
        var r2 = Math.floor(Math.random() * 10);
        var r3 = Math.floor(Math.random() * 10);
        var name = 'getJSONP' + a[r1] + a[r2] + a[r3];
        var cbname = 'getJSONP.' + name; //作為jsonp函數的屬性
        if (url.indexOf('?') === -1) {
            url += '?jsonp=' + cbname;
        } else {
            url += '&jsonp=' + cbname;
        }
        var script = document.createElement('script');
        //定義被腳本執行的回調函數
        getJSONP[name] = function(e) {
            try {
                callback && callback(e);
            } catch (e) {
                //
            } finally {
                //最後刪除該函數與script元素
                delete getJSONP[name];
                script.parentNode.removeChild(script);
            }

        }
        script.src = url;
        document.getElementsByTagName('head')[0].appendChild(script);
    }
    // 跨域調用
    getJSONP('http://class.imooc.com/api/jsonp', function(response) {
        console.log(response);
});

jsonajax登錄功能

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Register</title>
   <meta charset="utf-8">
   <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
   <div class="register">
          <p class="title" id="title">
                  <span>登 錄</span>
                  <span class="current">註 冊</span>
          </p>
          <div class="form">
                  <div>
                      <span>+86</span>
                      <input type="text" name="user" id="user" placeholder="請輸入註冊手機號" autocomplete="off"/>
                      <i id="user_icon"></i>
                      <p class="info" id="user_info"></p>
                  </div>
                  <div>
                      <input type="password" name="pwd" id="pwd" placeholder="請設置密碼">
                      <i id="pwd_icon"></i>
                      <p class="info" id="pwd_info"></p>
                  </div>
                  <p class="button">
                      <a href="javascript:void(0)" id="sigup-btn" class="btn show">註 冊</a>
              <a href="javascript:void(0)" id="login-btn" class="btn">登 錄</a>
                  </p> 
          </div>
   </div>
   <script type="text/javascript" src="js/ajax.js"></script>
   <script type="text/javascript">
        var user = document.getElementById("user"),
            pwd = document.getElementById("pwd"),
            sigup = document.getElementById("sigup-btn"),
            login = document.getElementById("login-btn"),
            titles = document.getElementById("title").getElementsByTagName("span");
            userInfo = document.getElementById("user_info"),
            userIcon = document.getElementById("user_icon")
            pwdInfo = document.getElementById("pwd_info"),
            pwdIcon = document.getElementById("pwd_icon"),
            userReg = /^1[3578]\d{9}$/,
            pwdReg = /^\w{5,12}$/,
            isRepeat = false;       // 記錄用戶名是否被占用
         // 檢測用戶
         function checkUser(){
            var userVal = user.value;
            // 驗證手機號是否有效
            if(!userReg.test(userVal)){
                userInfo.innerHTML = '手機號碼無效!';
                userIcon.className = 'no';
            }else{
                userInfo.innerHTML = '';
                userIcon.className = '';
                // 發起請求
                $.ajax({
                    url:'http://localhost/register/server/isUserRepeat.php',
                    data:{username:userVal},
                    success:function(data){          
                        if(data.code == 1){
                            userIcon.className = 'ok';
                            isRepeat = false;
                        }else if(data.code == 0){
                            userIcon.className = 'no';
                            isRepeat = true;
                            userInfo.innerHTML = data.msg;
                        }else{
                            userInfo.innerHTML = '檢測失敗,請重試...';
                        }
                    }
                })
            }
         }

         // 檢測密碼
         function checkPwd(){
             var pwdVal = pwd.value;
             if(!pwdReg.test(pwdVal)){
                 pwdInfo.innerHTML = '請輸入5到12位的字母、數字及下劃線';
                 pwdIcon.className = 'no';
             }else{
                 pwdInfo.innerHTML = '';
                 pwdIcon.className = 'ok';
             }
         }

         // 註冊
         function register(){
             var user_val = user.value,
                 pwd_val = pwd.value;
             // 如果手機號有效且沒有被占用,同時密碼合法,方可註冊
             if(userReg.test(user_val) && pwdReg.test(pwd_val) && !isRepeat){
                // 發起請求,實現註冊
                $.ajax({
                    url:"http://localhost/register/server/register.php",
                    method:"post",
                    data:{username:user_val,userpwd:pwd_val},
                    success:function(data){
                        alert("註冊成功,請登錄!");
                        // 調用顯示登錄界面
                        showLogin();
                        // 清空文本框
                        user.value = "";
                        pwd.value = "";
                    },
                    error:function(){
                        pwdInfo.innerHTML = '註冊失敗,請重試!';
                    }
                })
             }
         }

         // 顯示登錄
         function showLogin(){
             // 載入登錄界面,登錄高亮顯示
             titles[0].className = "current";
             titles[1].className = "";
             login.className = "show";
             sigup.className = "";
         }

         // 顯示註冊
         function showSigup(){
             // 載入註冊界面,註冊高亮顯示
             titles[1].className = "current";
             titles[0].className = "";
             login.className = "";
             sigup.className = "show";
         }
      
        // 綁定事件,檢測用戶的有效性及是否註冊過
        user.addEventListener("blur",checkUser,false);

        // 綁定事件,檢測密碼的有效性
        pwd.addEventListener("blur",checkPwd,false);

        // 註冊
        sigup.addEventListener("click",register,false);

        // 登錄高亮
        titles[0].addEventListener("click",showLogin,false);

        // 註冊高亮
        titles[1].addEventListener("click",showSigup,false);
   </script>
</body>
</html>

style.css

*{
    margin:0;
    padding:0;
}

body{
    background:#333;
}

.register{
    width:300px;
    height:270px;
    margin:80px auto;
    padding:15px 30px;
    background:#eee;
    border-radius:5px;
}

.title{
    height:35px;
}

.title span{
    font-size:16px;
    font-weight:bold;
    color:#666;
    margin-right:30px;
    cursor:pointer;
}

.title span.current{
    color:#f00;
}

.form div{
    width:290px;
    height:30px;
    border-radius:8px;
    background:#fff;
    margin-bottom:40px;
    padding:8px 10px;
    position:relative;
}

.form div span{
    display:inline-block;
    padding-top:8px;
    padding-right:3px;
    color:#666;
}

.form div input{
    border:none;
    outline:none;
    font-size:17px;
    color:#666;
    background:none;
}

.form div i{
    position:absolute;
    width:16px;
    height:16px;
    right:12px;
    top:14px;
}

.form div i.ok{
    background:url(../img/icon.png) no-repeat 0 -67px;
}

.form div i.no{
    background:url(../img/icon.png) no-repeat -17px -67px;
}

.form .info{
    margin-top:22px;
    color:#f00;
    padding-left:2px;
}

.button{
    padding-top:7px;
}

.button a{
    display:none;
    width:100%;
    height:45px;
    line-height:45px;
    text-align:center;
    text-decoration:none;
    background:#f20d0d;
    color:#fff;
    border-radius:30px;
    font-size:16px;
}

.button a.show{
    display:block;
}

ajax.js

var $ = {
    ajax:function(options){
        var xhr = null,          // XMLHttpRequest對象
            url = options.url,   // url地址
            method = options.method || 'get', // 傳輸方式,預設為get
            async = typeof(options.async) === "undefined"?true:options.async,
            data = options.data || null,      // 參數
            params = '',
            callback = options.success,       // ajax請求成功的回調函數                   
            error = options.error;
            // 將data的對象字面量的形式轉換為字元串形式
            if(data){
                for(var i in data){
                    params += i + '=' + data[i] + '&';
                }
                params = params.replace(/&$/,"");
            }
            // 根據method的值改變url
            if(method === "get"){
                url += '?'+params;
            }
        if(typeof XMLHttpRequest != "undefined"){
            xhr = new XMLHttpRequest();
        }else if(typeof ActiveXObject != "undefined"){
            // 將所有可能出現的ActiveXObject版本放在一個數組中
            var xhrArr = ['Microsoft.XMLHTTP','MSXML2.XMLHTTP.6.0','MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP.2.0'];
            // 遍歷創建XMLHttpRequest對象
            var len = xhrArr.length;
            for(var i = 0;i<len;i++){
                try{
                    // 創建XMLHttpRequest對象
                    xhr = new ActiveXObject(xhrArr[i]);
                    break;
                }
                catch(ex){

                }
            }
        }else{
            throw new Error('No XHR object availabel.');
        }
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                if((xhr.status >=200 && xhr.status <300) || xhr.status === 304){
                    callback && callback(JSON.parse(xhr.responseText))
                }else{
                    error && error();
                }
            }
        }
        // 創建發送請求
        xhr.open(method,url,async);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xhr.send(params);
    },
    jsonp:function(){
        // 跨域
    }
}

isUserRepeat.php

<?php 
header('Content-Type:application/json');
$isUsername = array_key_exists('username',$_REQUEST); 
$username = $isUsername ? $_REQUEST['username'] : '';

if(!$username){
    $msg = printMsg('參數有誤',2);
    echo json_encode($msg);
    exit();
}

function printMsg($msg,$code){
    return array('msg'=>$msg,'code'=>$code);
}

// 記錄存儲用戶的文件路徑
$fileStr = __DIR__.'/user.json';

// 讀取現存的用戶名和密碼

$fileStream = fopen($fileStr,'r');

$fileContent = fread($fileStream,filesize($fileStr));
$fileContent_array = $fileContent ? json_decode($fileContent,true) : array();
fclose($fileStream);
// 判斷用戶名是否有重覆的

$isrepeat = false;

foreach($fileContent_array as $key=>$val){
    if($val['username'] === $username){
        $isrepeat = true;
        break;
    }
}

if($isrepeat){
    $msg = printMsg('用戶名重覆',0);
    echo json_encode($msg);
    exit();
}
$msg = printMsg('用戶名可用',1);
echo json_encode($msg);
?>

register.php

<?php 
header('Content-Type:application/json');
// 獲取前端傳遞的註冊信息 欄位為   username   userpwd
$isUsername = array_key_exists('username',$_REQUEST); 
$isUserpwd = array_key_exists('userpwd',$_REQUEST); 
$username = $isUsername ? $_REQUEST['username'] : '';
$userpwd = $isUserpwd ? $_REQUEST['userpwd'] : '';
function printMsg($msg,$code){
    return array('msg'=>$msg,'code'=>$code);
}

if(!$username || !$userpwd){
    $msg = printMsg('參數有誤',0);
    echo json_encode($msg);
    exit();
}

// 記錄存儲用戶的文件路徑
$fileStr = __DIR__.'/user.json';

// 讀取現存的用戶名和密碼

$fileStream = fopen($fileStr,'r');

$fileContent = fread($fileStream,filesize($fileStr));
$fileContent_array = $fileContent ? json_decode($fileContent,true) : array();
fclose($fileStream);
// 判斷用戶名是否有重覆的

$isrepeat = false;

foreach($fileContent_array as $key=>$val){
    if($val['username'] === $username){
        $isrepeat = true;
        break;
    }
}

if($isrepeat){
    $msg = printMsg('用戶名重覆',0);
    echo json_encode($msg);
    exit();
}

array_push($fileContent_array,array('username'=>$username,'userpwd'=>$userpwd));

// 將存儲的用戶名密碼寫入
$fileStream = fopen($fileStr,'w');
fwrite($fileStream,json_encode($fileContent_array));
fclose($fileStream);
echo json_encode(printMsg('註冊成功',1));

?>

user.json

[{"username":"zhangsan","userpwd":"zhangsan"},{"username":"lisi","userpwd":"lisi"},{"username":"134","userpwd":"sdfsdf"},{"username":"135","userpwd":"dsff"},{"username":"136","userpwd":"dsff"},{"username":"13521554677","userpwd":"sdfsdf"},{"username":"13521557890","userpwd":"sdfsdf"},{"username":"13521557891","userpwd":"sdfsdf"},{"username":"13810701234","userpwd":"sdfsdf"},{"username":"13810709999","userpwd":"shitou051031"},{"username":"13810709998","userpwd":"sdfsdfdsf"},{"username":"13412345678","userpwd":"shitou"}]

雜七雜八的知識點:

jQuery 點擊事件中觸發的方式:

mousedownmouseup事件滑鼠左鍵點擊和滑鼠右鍵點擊都是可以實現的;

 

clickdblclick事件只有滑鼠左鍵點擊才能實現

 

    // jquery渲染數據

    function renderData(data) {

        var str = "";

        $.each(data, function(index, obj) {

            str += '<a href="' + obj.linkUrl + '"><img src="' + obj.picUrl + '"></a>'

        })

        $("#banner_jq").html(str);

}

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 場景 AndroidStudio跑起來第一個App時新手遇到的那些坑: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103797243 使用相對佈局RelativeLayout實現簡單的登錄提示的佈局,效果如下 註: 博客: h ...
  • 最近有一些開發朋友問我應該怎樣提升自己的能力,回想起來做了這麼久 iOS 開發,我也有過那種“讓我做一個功能實現個需求我會做,但接下來怎樣提高我不知道。”的時期,這裡嘗試列一下 iOS 開發的相關技術,再說說在學習進階上我的一些想法。 iOS 技術棧 這裡按我的理解給 iOS 相關技術分個類,以工程 ...
  • 1.壓力測試monkey 通過cmd輸入下麵命令: 表示測試com.example.phonecall應用程式,隨機發送點擊/滑動/切換事件10000次,( -v -v -v)表示信息日誌為最高級,然後列印的信息傳到F:\monkey_log\test1.txt里. 如下圖所示: 2.單元測試 2. ...
  • This interface shows how a spring animation can be created by specifying a “damping” (bounciness) and “response” (speed). 這個交互顯示瞭如何通過指定“阻尼”(有彈性)和“響應”( ...
  • 場景 實現效果如下 註: 博客: https://blog.csdn.net/badao_liumang_qizhi 關註公眾號 霸道的程式猿 獲取編程相關電子書、教程推送與免費下載。 實現 新建Android項目,首先打開activity_main.xml 修改其為FrameLayout幀佈局管理 ...
  • gradle配置項 1. compileSdkVersion 用哪個 Android SDK 版本編譯你的應用。因此我們強烈推薦總是使用最新的 SDK 進行編譯。在現有代碼上使用新的編譯檢查可以獲得很多好處,避免新棄用的 API ,並且為使用新的 API 做好準備。 2. minSdkVersion ...
  • 一、數組 1、function(value, index, array) {} 【格式:】 function (value, index, array) => { // value 指 數組當前遍歷的值, index 指 數組當前遍歷的下標, array 指 當前數組 // ... 自定義函數行為 ...
  • 所謂響應式佈局,就是頁面會根據當前運行的設備的大小自行進行調整,實現方案主要有以下三種: 1)隱藏 例如在 PC 端的一些友情鏈接或者不重要的內容在移動端可以選擇隱藏起來。 2)換行 在 PC 端顯示一行的內容,由於移動端設備寬度比較小,所以可以選擇顯示為幾行。 3)自適應空間 例如,左邊元素給定一 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...