Vue3 项目里面使用 自己封装的 jsonp

 由于 vue-jsonp 在 vue3 中 测试不能用 ,有能用的包 欢迎留言

在网上找到一个有用的


function jsonp(setting){
  setting.data = setting.data || {}
  setting.key = setting.key||'callback'
  setting.callback = setting.callback||function(){} 
  setting.data[setting.key] = 'xxxx一样的'  //callback="xxxxxx"
  window."xxxxx一样的"= function(data){
    setting.callback (data);
  }

  var script = document.createElement('script')
  var query = []
  for(var key in setting.data){
    query.push( key + '='+ encodeURIComponent(setting.data[key]) )
  }
  script.src = setting.url + '?' + query.join('&')
  document.head.appendChild(script)
  document.head.removeChild(script)

}
如果路径后不用  callback=‘xxxx’
jsonp({
  url: 'http://api.jirengu.com/weather.php',
  callback: function(ret){
    console.log(ret)
  }
})
如果路径后用  callback=‘xxxx’
jsonp({
  url: 'http://photo.sina.cn/aj/index',
  key: 'callback' 实行况而定 ,
  /** 可选 data: {
    page: 1,
    cate: 'recommend'
  },*/
  callback: function(ret){
    console.log(ret)
  }
})

我的地址

http://127.0.0.1:3333/api/list?callback=callbacklocation

调用 onMounted

initScript({
  url: 'http://127.0.0.1:3333/api/list',
  key: 'callback',
  callback: function(ret:any){
    console.log(ret)
  }

函数

let initScript = (setting: any) => {
  // var frame = document.createElement("script");
  // frame.src = "http://127.0.0.1:3333/api/list?callback=callbacklocation";
  // document.body.append(frame);
  setting.data = setting.data || {};
  setting.key = setting.key || "callback";
  setting.callback = setting.callback || function () {};
  setting.data[setting.key] = "callbacklocation";
  window.callbacklocation = function (data:any) {
    setting.callback(data);
  };

  var script = document.createElement("script");
  var query = [];
  for (var key in setting.data) {
    query.push(key + "=" + encodeURIComponent(setting.data[key]));
  }
  script.src = setting.url + "?" + query.join("&");
  document.head.appendChild(script);
  document.head.removeChild(script);
};

原文地址

https://zhuanlan.zhihu.com/p/541743336https://zhuanlan.zhihu.com/p/541743336

感谢 csdn 的实时保存功能 ,刚才测试一下地址 以为内容丢了。。。

你可能感兴趣的:(Vue3,vue,vue.js,javascript,前端)