Ajax基本使用二

前后端互相:

<button id="btn">321</button>
<script>

function ajax(opts){
    var httpreq= new XMLHttpRequest(),
        url_con='';
    for(var key in opts.data){
        url_con+=key+'='+opts.data[key]+'&';
    }
    url_con = url_con.substr(0, url_con.length - 1);
    httpreq.onreadystatechange= function(){
        if(httpreq.readyState == 4&& httpreq.status== 200){
                opts.success(httpreq.responseText);
        }
        if(httpreq.status== 403){
                opts.error();
        }
    }
    if(opts.type=='post'){
        httpreq.open(opts.type, opts.url, true);
        httpreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        httpreq.send(url_con);  
    }
    if(opts.type=='get'){
        httpreq.open(opts.type, opts.url+'?'+url_con, true);
        httpreq.send();     
    }
}

document.querySelector('#btn').addEventListener('click', function(){
    ajax({
        url: 'test.php',   //接口地址
        type: 'get',               // 類型, post 或者 get,
        data: {
            username: 'xiaoming',
            password: 'abcd1234'
        },
        success: function(ret){
            console.log(ret);       // {status: 0}
        },
        error: function(){
           console.log('出錯了')
        }
    })
});

</script>

php:

<?php 
    echo $_GET["username"];
    echo $_GET['password'];
?>

如何從后端獲取數據操作前端:

(忽視ajax部分代碼,不想重新寫了,后端僅傳送了個5過來)

var button=document.querySelector('#btn'),
    div_fa=document.querySelector('#example');
var j=3;

function ajax(opts){
    var httpreq= new XMLHttpRequest(),
        url_con='';
    for(var key in opts.data){
        url_con+=key+'='+opts.data[key]+'&';
    }
    url_con = url_con.substr(0, url_con.length - 1);
    httpreq.onreadystatechange= function(){
        if(httpreq.readyState == 4&& httpreq.status== 200){
                opts.success(addline(httpreq.responseText));
        }
        if(httpreq.status== 403){
                opts.error();
        }
    }
    if(opts.type=='post'){
        httpreq.open(opts.type, opts.url, true);
        httpreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        httpreq.send(url_con);  
    }
    if(opts.type=='get'){
        httpreq.open(opts.type, opts.url+'?'+url_con, true);
        httpreq.send();     
    }
}

function addline(p){
    for(var i=0;i<p;i++){
        var div_new=document.createElement("div");
        div_new.className='line';
        div_new.innerText='內容'+j++;
        div_fa.appendChild(div_new);
    }
}

button.addEventListener('click', function(){
    ajax({
        url: 'test.php',   //接口地址
        type: 'get',               // 類型, post 或者 get,
        data: {
            username: 'xiaoming',
            password: 'abcd1234'
        },
        success: function(ret){
            console.log(ret);       // {status: 0}
        },
        error: function(){
           console.log('出錯了')
        }
    })
});

php:

<?php 
    echo 5;
?>

登錄基本操作:

<body>
<div class="register">
    <h2>注冊</h2>
</div>
<div class="ct">
    <ul>
        <li>
            用戶名:&nbsp;&nbsp;&nbsp;<input id="username" type="text" placeholder=" &nbsp;&nbsp;用戶名(hunger已被注冊)">
            <span id="name_tip">只能是字母、數字、下劃線,3-10個字符</span>
        </li>
        <li>
            密碼:&nbsp;&nbsp;&nbsp; <input type="password" id="psw">
            <span id="psw_tip">大寫字母、小寫、數字、下劃線最少兩種,6-15個字符</span>
        </li>
        <li>
            再輸一次:&nbsp; <input type="password" id="psw_again" placeholder=" &nbsp;&nbsp;在輸入一次密碼">
            <span id="pswtip_again"></span>
        </li>
    </ul>
</div>
<button id="btn">注冊</button>
<script>
//封裝ajax
function ajax(opts){
    var xhr=new XMLHttpRequest();
    xhr.onreadystatechange=function (){
        if(xhr.readyState==4&&xhr.status==200){
            var json=JSON.parse(xhr.responseText);
            opts.success(json)
            }
        if(xhr.readyState==4&&xhr.status==404){
            opts.onError()
            }
    }
    var dataStr="";
    for(var key in opts.data){
        dataStr+=key+"="+opts.data[key]+"&";
    }
    dataStr=dataStr.substr(0,dataStr.length-1);
    dataStr+="&"+new Date().getTime();
    //利用Date().getTime()返回值的毫秒數不斷變化,制止緩存
    if(opts.type.toLowerCase()=='post'){
        xhr.open(opts.type,opts.url,ture)
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xhr.send(dataStr)
    }
    if (opts.type.toLowerCase()=='get') {
        xhr.open(opts.type,opts.url+'?'+dataStr,true)
        xhr.send()
    }
}

//獲取input、span、button
var username=document.getElementById('username');
var name_tip=document.getElementById("name_tip");
var psw=document.getElementById('psw');
var psw_tip=document.getElementById('psw_tip');
var psw_again=document.getElementById('psw_again');
var pswtip_again=document.getElementById('pswtip_again');
var btn=document.getElementById('btn');
//驗證用戶名
function isValidUsername(str){
    var reg=/^\w{3,10}$/;
    return reg.test(str);
}
//驗證用戶名是否已被注冊
username.addEventListener('change',function(){
    ajax({
        url:'test.php',
        type:'get',
        data:{
            username:username.value,
        },
        success:function(ret){
            dealWith(ret)
        },
        error:function(){
            onError()
        }
    })
});

function dealWith(ret){
    if(ret==0){
        name_tip.innerText='該用戶名已存在';
        username.style.border="1px solid red";
    }
    if(ret==1&&isValidUsername(username.value)){
        name_tip.innerText='該用戶名可用';
        username.style.border="1px solid gray";
    }
    if(!isValidUsername(username.value)){
        name_tip.innerText = '該用戶名格式不正確';
        username.style.border = "1px solid red";
    }
}
function onError(){
    alert("oh,出錯了...")
}
//判斷密碼
function isValidPsw(str){
    var reg1=/(^\d{6,15}$)|(^[A-Z]{6,15})$|(^[a-z]{6,15}$)|(^_{6,15}$)|(^\w{0,5}$)/
    var reg2=/^\w{6,15}$/
    if(reg1.test(str)){
        return
    }
    if(reg2.test(str)){
        return true
    }
}
//判斷密碼格式
//第一次輸入
psw.addEventListener('change',function(){
    if(!isValidPsw(psw.value)){
        psw_tip.innerText="密碼格式不正確";
        psw.style.border="1px solid red";
    }else{
        psw_tip.innerText="";
        psw.style.border="1px solid gray";

    }
})
//再次輸入密碼
psw_again.addEventListener('change',function(){
    if(psw_again.value==""){
        pswtip_again.innerText="密碼不能為空";
        psw_again.style.border="1px solid red";
    }
    else if(psw_again.value==!psw.value){
        pswtip_again.innerText="兩次密碼輸入不一致";
        psw_again.style.border="1px solid red";
    }
    else if(!isValidPsw(psw_again.value)){
        pswtip_again.innerText="密碼格式不正確";
        psw_again.style.border="1px solid red";
    }
    else{
        pswtip_again.innerText='';
        psw_again.style.border="1px solid gray";
    }
})
//btn的注冊驗證
btn.addEventListener('click',function(){
    // e.preventDefault();
    if(isValidUsername(username.value)&&psw.value==psw_again.value){
        alert('注冊中...')
    }else{
        alert('信息不符,請重新輸入')
    }
})
    
</script>
</body>

php

<?php 
    $name=$_GET['username'];
    if($name=="hunger"){
    echo 0;
    }else{
    echo 1;
   }
?>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容