jsonp

前端之家收集整理的这篇文章主要介绍了jsonp前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
$(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函数.

猜你在找的Json相关文章