您的位置:首页 > Web前端 > JQuery

跨域访问:jquery ajax jsonp的实现方法(jsp和action方式)

2014-08-23 19:22 651 查看
[javascript]

<mce:script language="javascript"><!--

$(function(){

$.ajax({

type: "get",

url: "www.sssss.com/ddd.do",

data: {

area : "ddd",

areaid : "2",

categorySz : ["",

"",

"",

"",

"",

"208",

"",

"",

"205",

"205",

"206"

,"207,250,251,252,253"

,"207,254"

,"207,255"

,"207,256"

,"207,257"

,"207,258"

,"207,259"],

typeSz : ["520,1201,201",

"520,1201,202",

"520,1202",

"520,1203",

"520,1204",

"",

"521,1201,201",

"521,1201,202",

"1201,202",

"1202"

, ""

, ""

, ""

, ""

, ""

, ""

, ""

, ""],

categoryOrSz : ["",

"",

"",

"",

"",

"",

"",

"",

"",

""

, ""

, "250,251,252,253"

, ""

, ""

, ""

, ""

, ""

, ""]},

dataType : "jsonp",

jsonp: "callback",

async: false,

cache: false,

success: function(data){

if (data != null && data != "") {

}

}

});

});

// --></mce:script>

服务器端:

代码很简单,就是输出一个字符串
比如正常输出json应该是:[{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]
jsonp 则输出: jsonpcallback([{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]) 其中“jsonpcallback”是客户端传过来的

[java] view plaincopy

/**

*

* @param form

* @param request

* @param response

* @return

* @throws Exception

*/

public String ajaxGetMybusAllDataJsonp(ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws Exception {

String callback = request.getParameter("callback");

JSONObject res = new JSONObject();

/*

* 处理方法

*

*/

res.put("d", "dddd");

// 可以避免前台显示出现乱码

response.setContentType("text/html");

response.setCharacterEncoding("utf-8");

PrintWriter out = response.getWriter();

out.print(callback + "(" + res.toString() + ")");

out.flush();

out.close();

return null;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: