数据交互之JSONP
- JSONP(JSON with Padding)是json一种“使用模式”:让当前网站从别的域名(网站)获取资料。
- 返回数据格式:以函数调用形式返回
eg: getData({“result”: {“key1”: “value1”, …}); - 获取数据:
<body>
<p id="test-jsonp">placehoder</p>
<button type='button' onclick="getPrice()">刷新</button>
</body>
<script>
//(1)准备好函数接受处理数据:
//data即getPrice中js.src传入的返回结果, 是一个JSON字符串
function showPrice(data){
var p=document.getElementById("test-jsonp");
p.innerHTML="当前价格:"+
data['0000001'].name +': ' +
data['0000001'].price + ';' +
data['1399001'].name + ': ' +
data['1399001'].price;
}
//(2)给页面动态加一个<script>节点,相当于动态读取外域JavaScript资源,等待接收回调
//点击"刷新"按钮时, 从'http://api.money.126.net/data/feed/0000001,1399001'请求JSON字符串,并把请求结果传给自定义函数showPrice()
function getPrice(){
var js=document.createElement('script');
var head=document.getElementsByTagName("head")[0];
js.src= 'http://api.money.126.net/data/feed/0000001,1399001?callback=showPrice';
head.appendChild(js);
}
</script>
数据交互之CORS
**浏览器内部自动完成跨域访问请求,成功与否取决于服务器是否愿意给设置一个正确的Access-Control-Allow-Origin(响应头是否包含本域地址/*), 实现代码与同源访问相同
**API获取地址:https://blog.csdn.net/c__chao/article/details/78573737
<body>
<P id="test-jsonp"></P>
<p id="text-reponse-text"></p>
</body>
<script>
window.onload = function () {
//XMLHttpRequest对象
var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
function success(text) {
var newText = JSON.parse(text);
var textarea = document.getElementById("text-reponse-text");
var content = "作者: " + newText.result.author +
" " + newText.result.origin +
" " + newText.result.category +
" " + newText.result.content;
textarea.innerHTML = content;
}
function fail(code) {
var textarea = document.getElementById("text-response-text");
textarea.value = "erroe code: " + code;
}
request.onreadystatechange = function () {
if (request.readyState === 4) { // readyState属性:提供当前HTML的就绪状态
if (request.status === 200) {
alert("请求成功!");
return success(request.responseText); //responseText属性:服务器返回的请求响应文本
} else {
return fail(request.status);
}
} else {
console.log("HTTP请求还在继续");
}
}
//建立到服务器的新请求
request.open("GET", "http://api.apiopen.top/singlePoetry");
//向服务器发送请求
request.send();
//退出当前请求
//abort();
alert("请求已发送,请等待相应...");
}
</script>
练习封装AJAX
function ajax(method, url, params, done) {
method = method.toUpperCase();
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
//将params参数可传入object,原参数形式也可
if (typeof params === 'object') {
var tempArr = [];
for (var key in params) {
var value = params[key];
tempArr.push(key + '=' + value);
}
params = tempArr.join('&');
}
//采用"GET"请求时,若传参一般在url上处理
if (method === 'GET') {
url += '?' + params;
}
xhr.open(method, url);
//采用"POST"请求时,需要发送一个HTTP协议的头部文件(编码),告诉服务器客户端要下载的信息以及相关的参数
var data = null;
if (method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
data = params;
}
xhr.send(data);
xhr.onreadystatechange = function () {
var _this = this;
if (_this.readyState === 4) {
if (_this.status === 200) {
//通过done()函数将数据返回,让调用者处理
done(_this.responseText);
}
}
}
}
//callBack函数,参数为请求返回的数据,未处理数据
ajax('GET', 'http://api.apiopen.top/musicBroadcasting', 'id=1', callBack);
//ajax('GET', 'http://api.apiopen.top/musicBroadcasting', {id: 1});
//ajax('POST', 'http://api.apiopen.top/musicBroadcasting', {key1: "value1", key2: "value2"});
function callBack(dataR) {
console.log(dataR);
}
jQuery ajax使用
$(function () {
//以下url在服务器端已设置content-Type
//底层实现:
$.ajax({
url: 'http://api.apiopen.top/musicBroadcasting',
type: 'post', // method
//在线编码/解码:http://tool.oschina.net/encode?type=4
data: {id: 1, name: "张三"}, //上传服务器的参数,传递的参数会进行编码
//如果服务器未设置content-type,可客户端设置dataType:用于设置响应体的类型;与data参数无关
//dataType: 'json',
beforeSend: function () {
//在所有发送请求的操作(open, send)之前执行
},
success: function (res) {
//res: 拿到的响应体,会根据服务器响应的 content-type 自动转换为 对象
console.log(res);
},
error: function (xhr) {
//请求状态码不为200时才会执行
console.log(xhr)
},
complete: function (xhr) {
//请求完成(成功/失败)再执行
}
});
//高度封装的ajax
//res响应体根据服务器响应的 content-Type 转换数据格式
$.get('http://api.apiopen.top/musicBroadcasting', { }, function (res) {
//处理返回res
});
$.post('http://api.apiopen.top/musicBroadcasting', { }, function (res) {
//处理返回res
});
$.getJSON('http://api.apiopen.top/musicBroadcasting', { id: 1}, function (res) {
//处理返回res
});
//使用原则:
//1.确定请求方式
//2.使用快捷方式向服务器请求资源
})