原生ajax传值

来源:互联网 发布:mysql5.7数据库安装 编辑:程序博客网 时间:2024/06/13 12:54

只有两种传值方式:GET 和 POST方式

GET:

xmlhttp = new XMLHttpRequest();//异步执行函数xmlhttp.onreadystatechange=function(){    if (xmlhttp.readyState==4 && xmlhttp.status==200)    {        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;    }}xmlhttp.open("GET","target.php?tid=1",true);xmlhttp.send();//open里面函数值分别是“传值方式”、“目标网页”、“是否异步”,send中不用写任何东西

POST:

xmlhttp = new XMLHttpRequest();//异步执行函数xmlhttp.onreadystatechange=function(){    if (xmlhttp.readyState==4 && xmlhttp.status==200)    {        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;    }}xmlhttp.open("POST","target.php",true);xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlhttp.send("user_id="+getCookie("user_id")+"&"+"user_pwd="+getCookie("user_pwd"));

注意:

1.POST第二行要设置响应头,固定的!!!!!!
2.POST发送的数据用&隔开,千万不能用错,虽然传送的是cookie值,但并不是直接将cookie写上去(cookie是用分号隔开)
3.在服务器那边的php直接就能用$_POST["user_id"]来获取数据(好久才跳出来的坑)
4.xmlhttp.onreadystatechange()函数是异步执行的,要等到服务器返回了数据才执行,所以书写在哪里都行,使用该函数的前提是“是否异步”为true
5.如果“是否异步”为false,则需要将xmlhttp.onreadystatechange()函数写在xmlhttp.send()后面

原创粉丝点击