Json與Ajax(註冊實例)

須要在服務器上進行哈javascript

jquery的ajax方法:php

    // 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函數css

    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登陸功能html

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.cssjava

*{
    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.jsjquery

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.phpajax

<?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.phpjson

<?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.jsonapi

[{"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);

}

相關文章
相關標籤/搜索