只说异步,异步
由于script能跨域获取数据,因此我们能方便的利用此特点跨域获取数据,虽然只支持get方式,但一般条件下能满足基本需求,以下为 jsonp的js实现:
本域上:
function createJs(url){
var oScript = document.createElement('script');
oScript.type='text/javascript';
oScript.src = url;
document.getElementsByTagName("head")[0].appendChild(oScript);
}
createJs("http://localhost:89/jingdong.json");
function _jsonpcallback(response){
console.log(response.list);
}
另一个域上"http://localhost:89/jingdong.json"上的数据为:
_jsonpcallback({
"list":[
{
"label":"美邦轻薄羽绒服",
"price":189,
"imgUrl":"http:localhost:88/images/p(1).jpeg"
},
{
"label":"韩版中长款棉衣",
"price":159,
"imgUrl":"http:localhost:88/images/p(1).jpeg"
},
])
其中_jsonpcallback为自己命名的回调函数名
jq在此基础上封装了一个ajax方法, 通过参数的设置,此方法能以jsonp的方式异步获取,省去了以上繁琐步骤,增加了跨域操作数据的灵活性,下列为jq的ajax:
$.ajax({
url: "http://localhost:89/jingdong.json",
type: "GET",
dataType: "jsonp",
corssDomain: true,
jsonp: "callback", //重写回调函数名
jsonpCallback: "_jsonpcallback", //设置回调函数名称 另一个域上json数据需用—_jsonpcallback()包裹
success: function(response){
console.log(response.list); //返回值是js对象
}
})
参数对象属性众多,此处只用到几个简单的
$.getJSON为jsonp方式调用ajax的简写形式
vue中的跨域与jq很相似:
getData: function () {
this.$http.jsonp("http://localhost:89/jingdong.json", {params:{},jsonpCallback:"_jsonpcallback"}).then(function (response) {
alert(response.data);
})
}
这样写需要引入vue-resource, 话说已经将要被axios取代了(不了解这个,假的吧)
笔者水平极其有限, 还望各位给予指正