App下載

html怎么寫post請(qǐng)求?實(shí)現(xiàn)方法有哪幾種方法?

猿友 2021-06-16 11:10:18 瀏覽數(shù) (7444)
反饋

在我們的學(xué)習(xí)中前端是一門比較容易入門的語言,當(dāng)然入門容易并不是說很簡單,前端語言在越往后學(xué)的就需要越多我們掌握的就需更多的精力放在上面,那么在前端中“html怎么寫post請(qǐng)求?有哪幾種方法?”這個(gè)問題中,小編為大家整理的一些相關(guān)的資料。


1.為什么要用post請(qǐng)求?

因?yàn)樵谖覀兪褂?post?請(qǐng)求的時(shí)候用戶在涉及有關(guān)于密碼和隱私的內(nèi)容時(shí),不會(huì)在地址欄上面看到我們的內(nèi)容起到了保護(hù)作用,所以這就是為什么要使用?post?請(qǐng)求的原因。


2.方法一:

我們通過使用傳統(tǒng)的方式來對(duì)瀏覽器進(jìn)行?post?請(qǐng)求,代碼如下:

var postData = {
    "name1": "value1",
    "name2": "value2"};
postData = (function(obj){ // 轉(zhuǎn)成post需要的字符串.
    var str = "";
    for(var prop in obj){
        str += prop + "=" + obj[prop] + "&"
    }
    return str;
})(postData);
var xhr = new XMLHttpRequest();
xhr.open("POST", "../module", true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
    var XMLHttpReq = xhr;
    if (XMLHttpReq.readyState == 4&&XMLHttpReq.status == 200) {
            var text = XMLHttpReq.responseText;
            console.log(text);
        }
};
xhr.send(postData);

3.方法二:

采用虛擬表單進(jìn)行提交?post?請(qǐng)求,代碼如下:

function post(URL, PARAMS) {      
    var temp = document.createElement("form");      
    temp.action = URL;      
    temp.method = "post";      
    temp.style.display = "none";      
    for (var x in PARAMS) {      
        var opt = document.createElement("textarea");      
        opt.name = x;      
        opt.value = PARAMS[x];      
        // alert(opt.name)      
        temp.appendChild(opt);      
    }      
    document.body.appendChild(temp);      
    temp.submit();      
    return temp;      
}          
//調(diào)用方法 如      
post('pages/statisticsJsp/excel.action', {html :prnhtml,cm1:'sdsddsd',cm2:'haha'});

總結(jié):

對(duì)于“html怎么寫post請(qǐng)求?實(shí)現(xiàn)方法有哪幾種方法?”這個(gè)問題,小編為大家分享的內(nèi)容就是這樣的了,當(dāng)然如果你有更好的方式或者想法也可以和大家一起分享學(xué)習(xí),對(duì)于在前端中的其他問題或者難點(diǎn)我們都可以在W3cschool中搜索相關(guān)的問題和知識(shí)點(diǎn),在這個(gè)平臺(tái)中都有很多的資料可以提供給大家使用和學(xué)習(xí)。


0 人點(diǎn)贊