ajax的具体步骤

执念博客
2017-10-06 / 0 评论 / 68 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年05月05日,已超过1087天没有更新,若内容或图片失效,请留言反馈。
广告

点击广告查看隐藏内容....

今天给大家介绍的是ajax的具体步骤,数据的提交最常用的就是“get”方式和“post”方式,因此下面介绍的就是ajax的这两种方式
第一种就是“get”方式:

[code lang="js"]
function creatXhr(){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
//ie5,ie6不支持XMLHttpRequest
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
var xhr = creatXhr();
if(xhr != null){
xhr.open("get","server.php?name=guo",true);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
doResponse(xhr);
}else{
alert("请求出错!");
}
}
}
xhr.send(null);
}
function doResponse(xhr){
var str = xhr.responseText;//其中xhr.responseText就是后天传送过来的数据
alert(str);
}
[/code]

需要注意的是“get”方式中的xhr.send(null);代表发送的意思,里面必须是null,发送的数据在xhr.open中的url拼接而成。

第二种的“post”方式:

[code lang="js"]
function creatXhr(){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
//ie5,ie6不支持XMLHttpRequest
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
var xhr = creatXhr();
if(xhr != null){
xhr.open("post","server.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
doResponse(xhr);
}else{
alert("请求出错!");
}
}
}
xhr.send("name=li");
}
function doResponse(xhr){
var str = xhr.responseText;
alert(str);
}
[/code]

ajax的“post”方式比“get”方式多了一句xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");,这一句是必不可少的,要不然数据是发送不过去的。发送的数据在xhr.send()中拼接而成。

其中两种方式用的php文件中的代码也给大家,

[code lang="php"]
<?php
$name = $_REQUEST['name'];
if($name){
echo $name;
}else{
echo "error";
}
?>
[/code]

大家可以自行尝试,如果有什么疑问,可以在下方留言。

本文共 201 个字数,平均阅读时长 ≈ 1分钟

点击广告查看隐藏内容....

0

打赏

海报

正在生成.....

评论 (0)

语录
取消