ajax中get和post的说明及使用与区别(4)


<mce:script type="text/javascript"><!--
var xmlHttpRequest;
function createXMLHttpRequest(){
try
{
// Firefox, Opera 8.0+, Safari
xmlHttpRequest=new XMLHttpRequest();
}
catch (e)
{

// Internet Explorer
try
{
xmlHttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{

try
{
xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("您的浏览器不支持AJAX!");
return false;
}
}
}

}
//发送请求函数
function sendRequestPost(url,param){
createXMLHttpRequest();
xmlHttpRequest.open("POST",url,true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-
urlencoded");
xmlHttpRequest.onreadystatechange = processResponse;
xmlHttpRequest.send(param);
}
//处理返回信息函数
function processResponse(){
if(xmlHttpRequest.readyState == 4){
if(xmlHttpRequest.status == 200){
var res = xmlHttpRequest.responseText;
window.alert(res);
}else{
window.alert("请求页面异常");
}
}
}
//身份验证函数
function userCheck(){
var userName = document.loginForm.username.value;
var psw = document.loginForm.password.value;
if(userName == ""){
window.alert("用户名不能为空");
document.loginForm.username.focus();
return false;
}
else{
//var url = "Servlet/userLogin_do?userName="+userName+"&psw="+psw;
var url = "Servlet/userLogin_do";
var param = "userName="+userName+"&psw="+psw;
sendRequestPost(url,param);
}
}
// --></mce:script>
<mce:script type="text/javascript"><!--
var xmlHttpRequest;
function createXMLHttpRequest(){
try
{
// Firefox, Opera 8.0+, Safari
xmlHttpRequest=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("您的浏览器不支持AJAX!");
return false;
}
}
}
}
//发送请求函数
function sendRequestPost(url,param){
createXMLHttpRequest();
xmlHttpRequest.open("POST",url,true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-
form-urlencoded");
xmlHttpRequest.onreadystatechange = processResponse;
xmlHttpRequest.send(param);
}
//处理返回信息函数
function processResponse(){
if(xmlHttpRequest.readyState == 4){
if(xmlHttpRequest.status == 200){
var res = xmlHttpRequest.responseText;
window.alert(res);
}else{
window.alert("请求页面异常");
}
}
}
//身份验证函数
function userCheck(){
var userName = document.loginForm.username.value;
var psw = document.loginForm.password.value;
if(userName == ""){
window.alert("用户名不能为空");
document.loginForm.username.focus();
return false;
}
else{
//var url = "Servlet/userLogin_do?
userName="+userName+"&psw="+psw;
var url = "Servlet/userLogin_do";
var param = "userName="+userName+"&psw="+psw;
sendRequestPost(url,param);
}
}
// --></mce:script>


可以发现,GET方法根据地址栏解析参数,post根据sendRequestPost(url,param);中的param字符串解析参数,重要的是POST方法中需要添加在open();方法后需要添加xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");这句代码,不知道为什么,初学,加了就能传递参数了,日后研究。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wddjgy.html