Ajax的post提交数据 代码和原理:
<SCRIPT LANGUAGE=”javascript”>
<!–
function saveUserInfo()
{
//获取接受返回信息层
var msg = document.getElementById(”msg”);
var f = document.user_info;
var userName = f.user_name.value;
var userAge = f.user_age.value;
var userSex = f.user_sex.value;
//接收表单的URL地址
var url = “commit.ASPX”;
//需要POST的值,把每个变量都通过&来联接
var postStr = “name=”+ userName +”&age=”+ userAge +”&sex=”+ userSex;
//实例化Ajax
var ajax = null;
if(window.XMLHttpRequest){
ajax = new XMLHttpRequest();
}
else if(window.ActiveXObject){
ajax = new ActiveXObject(”Microsoft.XMLHTTP”);
else{
return;
//通过Post方式打开连接
ajax.open(”POST”,url,true);
//定义传输的文件HTTP头信息
ajax.setRequestHeader(”Content-Type”,”application/x-www-form-urlencoded”);
//发送POST数据
ajax.send(postStr);
//返回数据的处理函数
ajax.onreadystatechange = function(){
if (ajax.readyState == 4 && ajax.status == 200){
msg.innerHTML = ajax.responseText;
}
}
–>
</SCRIPT>
<form name=”user_info”>
姓名:<input type=”text” name=”user_name” /><br/>
年龄:<input type=”text” name=”user_age” /><br/>
性别:<input type=”text” name=”user_sex” /><br/>
<input type=”button” value=”提交表单” onClick=”saveUserInfo()”>
</form>
//构建一个接受返回信息的层:
<div id=”msg”></div>
请关注:移动互联网开发
谢谢关注 websites 博客!