1. 安装jsonp扩展
cnpm i vue-jsonp —save-dev
2. /src/main.js 引入
1 // 引入 vue-jsonp 2 import VueJsonp from 'vue-jsonp' 3 4 // 使用 vue-jsonp 5 Vue.use(VueJsonp, 5000)
3. 使用,JSONP的回调函数要写到 window 对象上,不然无法触发,如果有更好的方法请留言,谢谢
1 <template> 2 <div class="hello container"> 3 <h1>{{ msg }}</h1> 4 <button class="btn btn-primary" @click="sendJsonp">JSONP</button> 5 <ul id="list"></ul> 6 </div> 7 </template> 8 9 <script type="text/ecmascript-6"> 10 // 引入 vue-jsonp 11 import jsonp from 'vue-jsonp' 12 13 // 回调函数必须定义到 window 对象上 14 window.test = (data) => { 15 //获取外层 SECTION 16 const oList = document.getElementById('list'); 17 oList.className = 'list-group'; 18 //PHP json_encode() 返回的数据在JS为数组类名 19 const aDate = data; 20 21 for (var i = 0; i < aDate.length; i++) { 22 //创建 LI 标签 23 const oLi = document.createElement('li'); 24 oLi.className = 'list-group-item'; 25 //将数组中的信息添加到 LI 中 26 oLi.innerHTML = aDate[i]; 27 //将 LI 追加到 UL 中 28 oList.appendChild(oLi); 29 } 30 } 31 32 export default { 33 name: 'HelloWorld', 34 data () { 35 return { 36 msg: 'Welcome to Your Vue.js App' 37 } 38 }, 39 methods: { 40 sendJsonp() { 41 this.$jsonp('http://www.api.test/test/jsonp/index.php', { 42 // 回调函数 43 m: 'test', 44 name: 'MyName', 45 age: 20 46 }).then(json => { 47 48 }).catch(err => { 49 // Failed. 50 }) 51 } 52 } 53 } 54 </script>
4. 后端PHP测试代码
1 <?php 2 header('content-type:text/html;charset=utf-8'); 3 // http://www.api.test/test/02/index.php 4 $method = $_GET['m']; 5 $arr = array( 6 'linux', 7 'apache', 8 'mysql', 9 'php' 10 ); 11 12 $callBack = $method . '(' . json_encode($arr) . ')'; 13 14 echo $callBack;