• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
红炉一点雪cck
博客园    首页    新随笔    联系   管理    订阅  订阅

原生js---ajax---post方法传数据

<!DOCTYPE html>
    <html>
        <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
        <body>
            姓名:<input type="text" name="user" id="user" value="" />
            年龄:<input type="text" name="age" id="age" value="" />
            <button id="btn">点击</button>
        </body>
    <script>
        var btn=document.getElementById("btn");
            btn.=function(){
            var userval=document.getElementById("user").value;
            var ageval=document.getElementById("age").value;
            //1.创建ajax对象(此处兼容性的创建)
            var xhr=null;
            try{
            xhr=new XMLHttpRequest();
            }catch(e){
            xhr=new ActiveXObject("Microsoft.XMLHTTP");
            }
            //2.调用open方法(true----异步)
            xhr.open("post","links/2.post.php",true);
            //3.发送数据
            xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
            xhr.send("username="+userval+"&age="+ageval+"&timp"+new Date().getTime());
            //4.请求状态改变事件
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4){
                    if(xhr.status==200){
                    document.write(xhr.responseText)
                    }else{
                    alert("错误"+xhr.status)
                    }
                }
            }
        }
    </script>
</html>

 

posted @ 2018-11-14 22:31  红炉一点雪cck  阅读(7603)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3