码迷,mamicode.com
首页 > Web开发 > 详细

XMLHttpRequest Basic 认证

时间:2018-03-13 13:54:43      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:XMLHttpRequest基本验证

  • 前端(JS):
    a. 要点:
    技术分享图片
    b. 完整代码:
    <script>
    if(window.XMLHttpRequest){  // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{  // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    var async = true
    if(async === true){
        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState < 4){
                console.log(‘loading...‘)
            }else if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                xmlDoc=xmlhttp.responseText;
                console.log(xmlDoc)
            }else{
                console.log(‘fail...‘)
                xmlhttp.abort()
            }
        }
    }
    xmlhttp.open("POST",‘http://192.168.0.200/index.php‘,async);
    xmlhttp.withCredentials = true;
    xmlhttp.setRequestHeader("Authorization", "Basic " + btoa("user:pass"));
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(‘name=lee‘);
    if(async === false){
        xmlDoc=xmlhttp.responseText;
        console.log(xmlDoc)
    }
    </script>
  • 后端(PHP):
    <?php
    if(!(isset($_SERVER[‘PHP_AUTH_USER‘],$_SERVER[‘PHP_AUTH_PW‘])&&$_SERVER[‘PHP_AUTH_USER‘]==‘user‘&&$_SERVER[‘PHP_AUTH_PW‘]==‘pass‘)){
    header(‘WWW-Authenticate:Basic realm ="Restricted area"‘);
    }else{  // 验证成功
    echo "Success";
    }
  • XMLHttpRequest Basic 认证

    标签:XMLHttpRequest基本验证

    原文地址:http://blog.51cto.com/12173069/2085960

    (0)
    (0)
       
    举报
    评论 一句话评论(0
    登录后才能评论!
    © 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
    迷上了代码!