(一)JSON对象
在前后端进行数据交互时,有时需要对数据进行一些处理,利用json对象的两个方法,可以实现数据的相互转化:
(1)JSON.stringify:可以把一个对象转成对应字符串
(2)JSON.parse():把一个字符串转成对应的对象
(二)使用get时:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
window.οnlοad=function(){
var oBtn=document.getElementById("btn");
oBtn.οnclick=function(){
var xhr=null;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("get","2get.php?userName="+encodeURI("张三")+"&age=20&"+new Date().getTime(),true);
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
alert(xhr.responseText);
}
}
}
}
}
</script>
</head>
<body>
<input type="button" value="提交" id="btn"/>
</body>
</html>
php页面:
<?php
header('content-type:text/html;charset="utf-8"');
error_reporting(0);
$userName=$_GET['userName'];
$age=$_GET['age'];
echo "你的名字:{$userName},年龄是:{$age}";
注意使用get方法时,传递的参数放在url?后,由于这种方式会有浏览器缓存,所以一般传递参数时在后面加上一个随机数或者时间戳,同时如果传递的参数中含有中文,需要进行编码,使用encodeURL();
post方式:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
window.οnlοad=function(){
//使用post方式,不会存在像get一样的缓存问题,也不会出现中文乱码
var oBtn=document.getElementById("btn");
oBtn.οnclick=function(){
var xhr=null;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("post","2.post.php",true);
//发送时注意设置数据格式
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
//发送的数据通过send函数接收
xhr.send("username=李四&age=30");
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
alert(xhr.responseText);
}
}
}
}
}
</script>
</head>
<body>
<input type="button" id="btn" value="提交"/>
</body>
</html>
php页面:
<?php
header('content-type:text/html;charset="utf-8"');
error_reporting(0);
$username=$_POST['username'];
$age=$_POST['age'];
echo "你的名字是:{$username},你的年龄是:{$age}";
注意发送时,需要设置请求头,同时传递参数通过send()方法;
以上需要注意的点还有就是使用post方式提交,则后端需要使用post方式返回,使用get方式提交,则后端需要使用get方式返回。