JSON APIS and AJAX
用户界面是用来帮助人们如何使用程序,而应用编程接口(APIs)是用来帮助程序与其他程序交互。APIs 是计算机间相互通信的工具,专门用于发送和接受数据。当你理解了如何发送请求和处理数据后,你就可以在页面中使用 API 了,程序员们通常会使用 AJAX 技术来发起 API 请求。
AJAX 术语 是 Asynchronous JavaScript And XML 的首字母缩写,它不是一个单一技术,而是一系列技术的组合。它向服务器发出异步请求以传输数据,然后将返回的数据加载到页面中。正是因为 AJAX 是异步的,所以浏览器不会停止加载页面来等待服务器的响应,也无需刷新整个页面就可以将更新的数据插入页面。
异步能在多方面提升用户的体验,由于浏览器不用在渲染页面的时候等待服务器做出响应,因而页面的加载速度更快。请求和传输都在后台进行,不会中断用户当前的操作。当浏览器接受到新的数据的时候,只有特定的区域会刷新,这些特性很大程度上增强了单页应用程序的用户体验。
浏览器和服务器之间传输的数据通常使用一种叫 JSON(JavaScript Object Notation)的格式。JSON 类似于 JavaScript 的对象字面量语法,只是它是以字符串的形式传输,一旦接收,就可以将其转换成对象在脚本中使用。
JSON 和 Ajax:使用 onclick 属性处理点击事件
你希望代码仅在页面完成加载后执行。为此,你可将名为DOMContentLoaded的 JavaScript 事件附加到文档中。
document.addEventListener('DOMContentLoaded',function() {
// 当用户点击 id 为getMessage的元素时会触发事件
document.getElementById('getMessage').onclick=function(){};
});
JSON 和 Ajax:通过单击事件更改文本
在onclick
事件处理器中添加代码,改变message
元素内的文字为 "Here is the message"。
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick=function(){
document.getElementsByClassName("message")[0].innerHTML = "Here is the message";
}
});
JSON 和 Ajax:使用 XMLHttpRequest 方法获取 JSON
API(或叫应用程序编程接口)是计算机用来互相通信的工具。JSON 语法与 JavaScript 对象字面符号非常相似,JSON 具有对象属性以及其当前值,夹在{
和}
之间。
但是,JSON 是由 API 以bytes
形式传输的,你的程序以string
接受它。它们能转换成为 JavaScript 对象,但默认情况下它们不是 JavaScript 对象。 JSON.parse
方法解析字符串并构造它描述的 JavaScript 对象。
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick=function(){
const req = new XMLHttpRequest();
req.open("GET", '/json/cats.json', true);
req.send();
req.onload = function(){
const json = JSON.parse(req.responseText);
document.getElementsByClassName("message")[0].innerHTML = JSON.stringify(json);
}
};
});
JSON 和 Ajax:访问来自 API 的 JSON 数据
[ ] -> 方括号表示数组
{ } -> 大括号表示对象
" " -> 双引号表示字符串,它们还用于表示 JSON 中的键名
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick=function(){
req=new XMLHttpRequest();
req.open("GET",'/json/cats.json',true);
req.send();
req.onload=function(){
json=JSON.parse(req.responseText);
document.getElementsByClassName('message')[0].innerHTML=JSON.stringify(json);
console.log(json[2].codeNames[1])
};
};
});
JSON 和 Ajax:将 JSON 数据转换为 HTML
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick=function(){
req=new XMLHttpRequest();
req.open("GET",'/json/cats.json',true);
req.send();
req.onload=function(){
json=JSON.parse(req.responseText);
var html = "";
json.forEach(function(val){
var keys = Object.keys(val);
html += "<div class='cat'>"
keys.forEach(function(key){
html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
})
html += "</div><br>";
});
document.getElementsByClassName('message')[0].innerHTML=html;
};
};
});
JSON 和 Ajax:渲染数据源的图像
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick=function(){
req=new XMLHttpRequest();
req.open("GET",'/json/cats.json',true);
req.send();
req.onload=function(){
json=JSON.parse(req.responseText);
var html = "";
json.forEach(function(val) {
html += "<div class = 'cat'>";
html += "<img src='"+ val.imageLink + "' alt='" + val.altText + "'>";
html += "</div><br>";
});
document.getElementsByClassName('message')[0].innerHTML=html;
};
};
});
JSON 和 Ajax:预先过滤 JSON 以获得所需的数据
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick=function(){
req=new XMLHttpRequest();
req.open("GET",'/json/cats.json',true);
req.send();
req.onload=function(){
json=JSON.parse(req.responseText);
var html = "";
json = json.filter(function(val){
return (val.id !== 1);
});
json.forEach(function(val) {
html += "<div class = 'cat'>"
html += "<img src = '" + val.imageLink + "' " + "alt='" + val.altText + "'>"
html += "</div>"
});
document.getElementsByClassName('message')[0].innerHTML=html;
};
};
});
JSON 和 Ajax:根据地理位置数据找到用户的 GPS 坐标
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
document.getElementById("data").innerHTML="latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude;
})
}
JSON 和 Ajax:使用 XMLHttpRequest 方法发送数据
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('sendMessage').onclick=function(){
var userName=document.getElementById('name').value;
var req=new XMLHttpRequest();
req.open("POST",url,true);
req.setRequestHeader('Content-Type','text/plain');
req.onreadystatechange=function(){
if(req.readyState==4 && req.status==200){
document.getElementsByClassName('message') [0].innerHTML=req.responseText;
}
};
req.send(userName);
};
});