读书人

ajax基础解决方案

发布时间: 2012-08-16 12:02:16 作者: rapoo

ajax基础
register.php页面如下:

[code=HTML] <html>
<head>
<title> </title>
<script type= "text/javascript ">
function getXmlHttpRequest() {
var xmlHttp;

try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}catch (e) {

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

alert( "您的浏览器不支持AJAX! ");
return false;
}
}
}

return xmlHttp;
}

var myXmlHttpRequest = " ";
function checkUser() {

myXmlHttpRequest = getXmlHttpRequest();

if(myXmlHttpRequest) {
//post方式的url
var url = "/ajaxTest/registerProcess.php ";
var data = "username= "+$( 'username ').value;
//alert(url+ " "+data);

//post方式打开请求
myXmlHttpRequest.open( "post ",url,true);
//post方式给服务器发送请求必须先修改MINE类型
myXmlHttpRequest.setRequestHeader( "Content-Type ", "application/x-www-form-urlencode ");
//指定回调函数
myXmlHttpRequest.onreadystatechange=handle;
myXmlHttpRequest.send(data);

}
}

function $(id) {
return document.getElementById(id);
}

function handle() {
//回调函数被调用的几个状态
//alert(myXmlHttpRequest.readyState);
if(myXmlHttpRequest.readyState==4) {

alert( "服务器返回: "+myXmlHttpRequest.responseText);

}
}


</script>
</head>

<body>
<form action= " " method= "post ">
用户名字: <input type= "text " name= "username1 " id= "username ">
<input type= "button " onclick= "checkUser(); " value= "验证用户名 ">
<input style= "border-width:0;color:red " type= "text " id= "myres "> <br/>
用户密码: <input type= "password " name= "password "> <br/>
电子邮件: <input type= "text " name= "email "/>
<input type= "submit " value= "用户注册 ">
</form>



<form action= " " method= "post ">
用户名字: <input type= "text " name= "username2 "> <br/>
用户密码: <input type= "password " name= "password "> <br/>
电子邮件: <input type= "text " name= "email "/> <br/>
<input type= "submit " value= "用户注册 ">
</form>

</body>


</html> [/code]

registerProcess.php页面如下:

[code=PHP] <?php
header( "Content-Type: text/html;charset=utf-8 ");
header( "Cache-Control: no-cache ");
$userName = $_POST[ 'username '];

echo "ok ".$userName;
?> [/code]
问题:用POST方式发送请求时$_POST[ 'username ']没有取到值,用GET方式发送请求时$_GET[ 'username ']却可以取到值,这是怎么回事啊?

[解决办法]

JScript code
//myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencode");//===>少了一个d  myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 

读书人网 >Ajax

热点推荐