Ajax从零开始(一)
#记录Ajax-day01-01~07
基本步骤-代码
//创建ajax对象
var xhr = new XMLHttpRequest();
//2、告诉Ajax对象要向啊发送请求,以什么方式发送请求
//参数:1)请求方式 2)请求地址
xhr.open('get',"test.txt","true");
//发送请求
xhr.send();
//获取服务器端响应到客户端的数据
xhr.onload = function () {
console.log(xhr.responseText);
}
open():.open( 提交方式 提交地址 是否异步)
1、提交方式 --get(代码如上)
服务端响应的数据格式:服务器端大多数情况下会以JSON对象作为响应数据格式。当客户端拿到响应数据时,要将JSON数据和HTML字符串进行拼接,然后将拼接的结果展示在页面中。(代码如下)
<script type="text/javascript">
//创建ajax对象
var xhr = new XMLHttpRequest();
//2、告诉Ajax对象要向啊发送请求,以什么方式发送请求
//参数:1)请求方式 2)请求地址
//xhr.open('get',"test.json","true");
xhr.open('get','http://localhost/ajaxDemo/test.json');
//发送请求
xhr.send();
//获取服务器端响应到客户端的数据
xhr.onload = function () {
//console.log(xhr.responseText);
var responseText = JSON.parse(xhr.responseText);
console.log(responseText);
var str = '<h2>'+responseText.name+'</h2>';
document.body.innerHTML = str;
}
</script>
补充:请求参数传递:
xhr.open(‘get’,‘http://localhost/ajaxDemo/index06.json?’+params);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>
<input type="text" name="" id="username" value="" />
</p>
<p>
<input type="text" name="" id="age" value="" />
</p>
<p>
<input type="button" name="" id="btn" value="提交" />
</p>
<script type="text/javascript">
var btn = document.getElementById('btn');
var username = document.getElementById('username');
var age = document.getElementById('age');
btn.onclick = function(){
//创建ajac对象
var xhr = new XMLHttpRequest();
//获取用户在文本框中输入的值
var nameValue = username.value;
var ageValue = age.value;
//拼接请求参数
var params = 'username=' + nameValue + '&age=' + ageValue;
//配置Ajax对象------ ?+params
xhr.open('get','http://localhost/ajaxDemo/index06.json?'+params);
//发送请求
xhr.send();
//获取服务端响应的数据
xhr.onload = function(){
console.log(xhr.responseText);
}
}
</script>
</body>
</html>
1、提交方式 --post:
xhr.open('post','http://localhost/ajaxDemo/index06.json');
//设置请求参数格式类型(必须要)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
//发送请求
xhr.send(params);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>
<input type="text" name="" id="username" value="" />
</p>
<p>
<input type="text" name="" id="age" value="" />
</p>
<p>
<input type="button" name="" id="btn" value="提交" />
</p>
<script type="text/javascript">
var btn = document.getElementById('btn');
var username = document.getElementById('username');
var age = document.getElementById('age');
btn.onclick = function(){
//创建ajac对象
var xhr = new XMLHttpRequest();
//获取用户在文本框中输入的值
var nameValue = username.value;
var ageValue = age.value;
//拼接请求参数
var params = 'username=' + nameValue + '&age=' + ageValue;
//配置Ajax对象------ ?+params
xhr.open('post','http://localhost/ajaxDemo/index06.json');
//设置请求参数格式类型(必须要)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
//发送请求
xhr.send(params);
//获取服务端响应的数据
xhr.onload = function(){
console.log(xhr.responseText);
}
}
</script>
</body>
</html>