JSONP跨域请求在Vue中怎么用?一直报错

迷人的保艳 阅读 14

我在Vue项目里想用JSONP请求第三方接口,但总是失败,浏览器控制台提示“Uncaught ReferenceError: callback is not defined”。我试过动态创建script标签,也试过axios-jsonp插件,都不行。

下面是我现在写的代码,接口是百度搜索的suggest接口,应该支持JSONP:

<template>
  <div>{{ result }}</div>
</template>

<script>
export default {
  data() {
    return { result: '' }
  },
  mounted() {
    const script = document.createElement('script')
    script.src = 'https://suggestion.baidu.com/su?wd=前端&cb=callback'
    document.head.appendChild(script)
  },
  methods: {
    callback(res) {
      this.result = res.s[0]
    }
  }
}
</script>

这个callback方法根本没被调用,是不是作用域问题?该怎么正确绑定回调函数?

我来解答 赞 2 收藏
二维码
手机扫码查看
1 条解答
小朝阳
小朝阳 Lv1
哈,JSONP这个老古董问题我熟。你这代码的问题在于callback函数是挂在methods里的,但JSONP需要callback函数在全局作用域。

两个解决方案:

1. 简单粗暴的直接挂window上:


mounted() {
window.callback = (res) => {
this.result = res.s[0]
}
const script = document.createElement('script')
script.src = 'https://suggestion.baidu.com/su?wd=前端&cb=callback'
document.head.appendChild(script)
}


2. 更优雅的用jsonp库(推荐):
先安装 jsonp 这个包


import jsonp from 'jsonp'

methods: {
fetchData() {
jsonp('https://suggestion.baidu.com/su?wd=前端', null, (err, data) => {
if (!err) {
this.result = data.s[0]
}
})
}
}


第二种方式更靠谱,不用手动处理script标签和全局污染。JSONP这种上古技术现在确实用得少了,CORS才是王道,但遇到必须用JSONP的老接口也没办法。
点赞
2026-03-06 00:00