原生javascript實現ajax 傳送post請求
阿新 • • 發佈:2018-12-24
var postData = { "name1": "value1", "name2": "value2"}; postData = (function(obj){ // 轉成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) { if (XMLHttpReq.status == 200) { var text = XMLHttpReq.responseText; console.log(text); } } }; xhr.send(postData);