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

ajax的get post 同步与异步操作

// get 同步
function getSync(url,params,success,error){
    var xhr = new XMLHttpRequest();
    xhr.open('get',url+'?'+params,false);
    xhr.send();
    if(xhr.readyState == 4&& xhr.status==200){
        success(xhr.responseText);
    }else{
        error('error');
    }
}

调用

    <script src="./temp.js"></script>
    <script>
        getSync('http://127.0.0.1/11.28-1/index.php', 'name=jack&age=18', ok, err);
        //   success();
        function ok(res) {
            var one=JSON.parse(res)
            console.log(one.info[0]);
        }
        function err(res) {
            console.log(res);
        }
    </script>
 
// get 异步
function getAsync(url,params,success,error){
    var xhr = new XMLHttpRequest();
    xhr.open('get',url+'?'+params,true);
    xhr.send();
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if(xhr.status==200){
                success(xhr.responseText)
            }else{
                error('error');
            }
        }
    }
}
调用
    <script src="./temp.js"></script>
    <script>
        getAsync('http://127.0.0.1/11.28-1/index.php', 'name=jack&age=18', ok, err);
        //   success();
        function ok(res) {
            var one=JSON.parse(res)
            console.log(one.info[0]);
        }
        function err(res) {
            console.log(res);
        }
    </script>
 
// post 异步
function postAsync(url,params,success,error){
    var xhr = new XMLHttpRequest();
    xhr.open('post',url,true);
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
    xhr.send(params);
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if(xhr.status==200){
                success(xhr.responseText)
            }else{
                error('error');
            }
        }
    }
}
调用
   postAsync('http://127.0.0.1/11.28-1/index.php','name=rose&age=18',ok,err);

        function ok(res){
            var one=JSON.parse(res)
            console.log(one.info[0]);
        }
        function err(res){
            console.log(res);
        }
 

 

本文来自博客园,作者:刘先生的爱心博客,转载请注明原文链接:https://www.cnblogs.com/liu521125/p/17862117.html

一点一滴记录着学习html5 css3 和js 的时光
posted @ 2023-11-28 15:41  刘先生的爱心博客  阅读(81)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3