seven.kyo 发表于 2013-1-29 11:42:12

AJAX跨域请求问题 ---

这两天项目中有AJAX跨域请求的需求,于是查找相关资料,多数说是通过JSONP来实现,JSONP是什么?问问谷哥!

我的环境是 Jquery + Struts2



$.getJSON("http://somewebsite?keyword="+word+"&callback=?",   //回调函数    function(json) {handleResponse(parent, json);})//@paramkeyword   想Action传的所要用的参数.               callback   回调函数参数, 后面可以是"?", 当是"?"时,参数值由Jquery自动生成; 也可指定为某回调函数名  
Struts2  Action中的代码:
 
 
public String method(){//获取回调函数的函数名String callback = ServletActionContext.getRequest().getParameter("callback");if(keyword!=null &&!keyword.equals("")){   //通过传过来的keyword参数,检索数据库返回List   keys = keyService.getKeyWords(keyword);   //将List转换为JSON数组形式   JSONArray kes = JSONArray.fromObject(keys);    try {   //解决中文乱码问题HttpServletResponse response= ServletActionContext.getResponse();response.setContentType("text/html;charset=utf-8"); response.setHeader("Cache-Control", "no-cache");   //输出格式需为callback(即获取到的回调函数名)+(传回页面的内容)    response.getWriter().print(callback +"("+ kes.toString()+")");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return null;}    具体的原理去网上搜索一下看看!  刚刚测试通过 , 可实现!  
 
    进阶资料:https://www.ibm.com/developerworks/cn/web/wa-aj-jsonp2/
                 https://www.ibm.com/developerworks/cn/web/wa-aj-jsonp1/
    Ps: 好神奇!
页: [1]
查看完整版本: AJAX跨域请求问题 ---