美文网首页
javascript发送get/post

javascript发送get/post

作者: 510bb14393e1 | 来源:发表于2022-05-03 19:54 被阅读0次

1.发送GET

var httpRequest = new XMLHttpRequest(); //第一步:建立所需的对象
httpRequest.open('GET', '/MsgShow?', true); //第二步:打开连接  将请求参数写在url中  ps:"./Ptest.php?name=test&nameone=testone"
httpRequest.send(); //第三步:发送请求  将请求参数写在URL中
httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            console.log(httpRequest.responseText);
        }
    };  

2.发送POST

var xhr = new XMLHttpRequest();  
    var data = Math.round(new Date().getTime() / 100);
    var body= "msg="+encodeURIComponent("你好");
    xhr.open("POST", "/Msg" , true);  
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(body);  
    xhr.onreadystatechange = function() {    
        if (xhr.readyState == 4) { //证明服务器已经准备就绪
            if (xhr.status == 200) { //页面请求成功
                var txt = xhr.responseText; //表示取出数据
                console.log(txt);
            }    
        }  
    }

相关文章

网友评论

      本文标题:javascript发送get/post

      本文链接:https://www.haomeiwen.com/subject/fqjiyrtx.html