加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

jsonp

发布时间:2020-12-16 19:32:57 所属栏目:百科 来源:网络整理
导读:$(function () { debugger; test(); }) function test() { $.ajax({ url:'http://192.168.56.1:8080/study_web/JsonP',dataType:"jsonp",jsonpCallback:"receive",success:function (data) { alert(data.msg); } }) } function receive(data) { alert("recei
$(function () {
        debugger;
        test();
    })
    function test() {
        $.ajax({
            url:'http://192.168.56.1:8080/study_web/JsonP',dataType:"jsonp",jsonpCallback:"receive",success:function (data) {
                alert(data.msg);
            }
        })
    }

    function receive(data) {
        alert("receive");
    }

jQuery对jsonp的支持极为友好,在写法上与ajax请求并没亦多大区别,只需将dataType的值设置为jsonp,和发送一个可选参数jsonpCallback的回调函数,如果不去设置jsonpCallback在值,jQuery会生成一个随机的回调函数,发送到服务器端。jsonp同时也需要得到后台服务器的支持。

protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		// TODO Auto-generated method stub
		String callback=request.getParameter("callback");
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("msg","xxoo");
		PrintWriter out=response.getWriter();
		out.println(callback+"("+jsonObject.toString()+")");
		out.flush();
		out.close();
		//response.getWriter().append("Served at: ").append(request.getContextPath());
	}

后台需要接收前端发送过来的callback参数,返回

callback+"("+jsonObject.toString()+")"

这样格式的字符串,返回前端后会立即执行callback函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读