您当前的位置: 首页 >  json

梁云亮

暂无认证

  • 2浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Vue插件之vue-jsonp

梁云亮 发布时间:2020-11-11 12:34:46 ,浏览量:2

简介

axios不支持jsonp,所以需使用其他插件:vue-jsonp。vue-jsonp官网

使用JSONP主要是目的通过动态创建Script,动态拼接url,进而抓取数据,实现跨域。确切地说,AJAX请求由于同源影响,是不允许进行跨域请求的,而Script标签src属性中的链接却可以访问跨域的js脚本,利用这一特性,服务端不再返回JSON格式的数据,而是返回一段调用某个函数的JS代码,在src属性中进行调用,实现跨域。

示例
  • 前端代码 第一步:安装vue-resource模块,代码如下:

cnpm install vue-jsonp --save

第二步:在main.js中引入vue-resource并通过命令Vue.user()使用该插件

import VueJsonp from ‘vue-jsonp’ Vue.use(VueJsonp)

第三步:页面


  
    请求数据
    
      
        {{item}}
      
    
  


  export default {
    name: 'app',
    data() {
      return {
        users: []
      }
    },
    methods: {
      getData() {
        var url = 'http://127.0.0.1:8088/servlet/vue';
        this.$jsonp(url).then((response) => {
          console.log(response);
          this.users = response;
        }).catch((error) => {
          console.log(error);
        })
      }
    }, mounted() { //新新的时候数据就显示出来
      this.getData();
    }
  }

  • 服务器端代码:
@WebServlet(urlPatterns = "/servlet/vue")
public class VueServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        String callback = request.getParameter("callback");
        PrintWriter out = response.getWriter();

        List userList = new ArrayList();
        userList.add(new User(11, "zhangsan", '女'));
        userList.add(new User(22, "lisi", '女'));
        userList.add(new User(33, "wanger", '女'));
        userList.add(new User(44, "mazi", '男'));

        String json = new Gson().toJson(userList);
        System.out.println("json " + json);
        out.write(callback + "(" + json + ")");
    }
}
关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0420s