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參數,返回java

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

這樣格式的字符串,返回前端後會當即執行callback函數.ajax

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息