GET方法:
function btn_get_click(){ var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = handleResponse; // httpRequest.open("GET", "/user/login?user_name=" + encodeURIComponent(username) + "&password=" + // encodeURIComponent(password)); httpRequest.open("GET", "/course/schedule?termno=0&week=0"); httpRequest.send(null); } function handleResponse(e) { if (e.target.readyState == XMLHttpRequest.DONE){ document.getElementById("result").innerHTML = e.target.responseText; var responseTextJson = JSON.parse(e.target.responseText); alert(responseTextJson.length); alert(responseTextJson[0].classroom); // alert(responseTextJson.DATAINFO[0].PROJ_NAME); } }
GET方法是明文的,处理上面的类似用户名密码的其实要用POST方法.(非明文方式)
PSOT:
function clickLoin() { var yonghu = document.getElementById("username").value;//获取用户名 var mima = document.getElementById("password").value;//获取密码 var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = handleResponse; var getloin ="username="+yonghu+"&&password="+mima; httpRequest.open("post", "/login"); //以下这句在POST时要加上 httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); httpRequest.send(getloin); } function handleResponse(e) { if (e.target.readyState == XMLHttpRequest.DONE){ // var responseTextJson = JSON.parse(e.target.responseText); alert(e.target.responseText); } }
两者的区别:
补充:(题外话)
后端post接口开发者的想法:
post函数定义了请求的地址,参数,还有一个回调函数。
而post的概念就是
“我执行的时候,需要你给我地址和参数,然后我执行完了,就完了,但是如果开发人员你,需要用到我返回的数据和状态,你要用,怎么办呢?
那没关系,不是还有一个回调函数吗?我再提供一个回调函数给你,至于你想怎么用,就用这个回调函数实现,于是我只把返回的数据,状态放在参数列表里面,并且下一个”执行“你外部函数的命令,
具体怎么实现,你要怎么用,是你开发人员的事了。