ajax中的get和post说明
一.谈Ajax的Get和Post的区别 Get方式: Post方式:
总之,GET方式传送数据量小,处理效率高,安全性低,会被缓存,而POST反之。 使用get方式需要注意: (content)+"&id=1" ;
get.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Ajax技术get方式</title> <script type="text/javascript"> function checkname(){ var nm=document.getElementById('username').value; //对传递的参数(特殊符号&,=等)进行编码处理 //同时对汉字进行编码 //nm=encodeURIComponent(nm); var xhr=new XMLHttpRequest(); xhr.onreadystatechange =function(){ if(xhr.readyState==4) alert(xhr.responseText); } xhr.open('get','./get.php?name='+nm); xhr.send(null); } </script> </head> <body> <h2>ajax 用户名的校验get</h2> 用户名<input type="text" id="username" onblur="checkname()"/> 手机号码<input type="text" id="tel"/> </body> </html> get.php <?php print_r($_GET); ?> 使用Post方式需注意: 1.设置header的Context-Type为application/x-www-form-urlencode确保服务器知道实体中有参数变量.通常使用XmlHttpRequest对象的SetRequestHeader("Context-Type","application/x-www-form-urlencoded;")。例: xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); abc&sex=man&age=18以及var name=?abc&sex=man&age=18的写法都是错误的; 4.服务器端请求参数区分Get与Post。如果是get方式则$username = $_GET["username"]; 如果是post方式,则$username = $_POST["username"];
post.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Ajax技术post方式</title> <script type="text/javascript"> function checkname(){ var nm=document.getElementById('username').value; //对传递的参数(特殊符号&,=等)进行编码处理 //自动进行汉字编码 nm=encodeURIComponent(nm); //把用户名信息变为‘请求字符串’ var info="name="+nm+"&age=23"; //info=encodeURIComponent(info); var xhr=new XMLHttpRequest(); xhr.onreadystatechange =function(){ if(xhr.readyState==4) alert(xhr.responseText); } xhr.open('post','./post.php'); //post方式传送数据是模拟form表单传递数据 //form表单的post格式数据是通过xml形式传递给服务器的 xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); xhr.send(info); } </script> </head> <body> <h2>ajax 用户名的校验post</h2> 用户名<input type="text" id="username" onblur="checkname()"/> 手机号码<input type="text" id="tel"/> </body> </html> post.php <?php print_r($_POST); ?> Post和Get 方法有如下区别: get 方法用Request.QueryString["strName"]接收 注意: AJAX乱码问题 产生乱码的原因: gb2312:header('Content-Type:text/html;charset=GB2312'); utf8:header('Content-Type:text/html;charset=utf-8'); 注意:如果你已经按上面的方法做了,还是返回乱码的话,检查你的方式是否为get,对于get请求(或凡涉及到url传递参数的),被传递的参数都要先经encodeURIComponent方法处理.如果没有用encodeURIComponent处理的话,也会产生乱码. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |