java ajax post跨域请求传递json格式数据问题

来源:互联网 发布:中国加工贸易数据 编辑:程序博客网 时间:2024/06/05 04:35

java 后台实现ajax post跨域请求传递json格式数据获取json数据问题  



参考大神:http://blog.csdn.net/chunqiuwei/article/details/19924821

java后台:
public String ajaxProxy(Integer param1,String param2,String url, HttpServletRequest req){   
        JSONObject node = new JSONObject();         
 try {    
 node.put("param1", param1) ;
     node.put("param2", param2);                               
    } catch (JSONException e1) {  
        e1.printStackTrace();  
    }        
      
    // 使用POST方式向目的服务器发送请求  
    URL connect;  
    StringBuffer data = new StringBuffer();  
    try {  
        connect = new URL(url);  
        HttpURLConnection connection = (HttpURLConnection)connect.openConnection();  
        connection.setRequestMethod("POST");  
        connection.setDoOutput(true); 
        connection.setRequestProperty("Content-Type", "application/json");
         
        OutputStreamWriter paramout = new OutputStreamWriter(  
                connection.getOutputStream(),"UTF-8");  
        paramout.write(node.toString());  
        paramout.flush();  
  
        BufferedReader reader = new BufferedReader(new InputStreamReader(  
                connection.getInputStream(), "UTF-8"));  
        String line;              
        while ((line = reader.readLine()) != null) {          
            data.append(line);            
        }  
        paramout.close();  
        reader.close();  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
    return data.toString();  
}

前台jsp: 
$.post(
url,
{
param1:param1,
param2:param2,
url:url
},
function (data){
alert(data);
}
);  




AJAX跨域请求json数据的实现方法



我们都知道,AJAX的一大限制是不允许跨域请求。 不过通过使用JSONP来实现。JSONP是一种通过脚本标记注入的方式,它是可以引用跨域URL的js脚本,不过需要提供一个回调函数(必须在您自己的页面上),因此,你可以自己处理结果。 让我们看看JSONP的是怎么在jQuery,MooTools的,Dojo Toolkit中实现的。 


jQuery的JSONP
jQuery.getJSON方法:


Js代码 
  复制代码 代码如下:


  jQuery.getJSON("",{ 
    q: "Arsenal" 
},function(tweets) { 
    // Handle response here 
    ("Twitter returned: ",tweets); 
}); 




或者 类似


Js代码 
  复制代码 代码如下:


  $.ajax({ 
                type:"get", 
                data:"random="+Math.random(), 
                url:url, 
                dataType:"jsonp", 
                jsonp:"callback", 
                success:function(data){ 
                      $.each(data, function(key, val) { 
                        $("#myDiv"l($("#myDiv"l()+val.cvalue+"</br>"); 
                      }); 
                } 
            }); 




回调方法的参数 通过getJSON 就可以获取 到json对象


MooTools JSONP
MooTools 需要Request.JSONP Class , 可以从这里下载MooTools More .  选择Request.JSONP,
这样 从另一个域获取json就是小菜一碟了.


Js代码 
  复制代码 代码如下:


  new Request.JSONP({ 
    url: "", 
    data: { 
        q: "Arsenal" 
    },//提交的参数, 没有参数可以不写 
        callbackKey: 'jsoncallback',//自己定义回调函数的参数名称 
        onComplete: function(tweets) { 
        // Log the result to console for inspection 
        ("Twitter returned: ",tweets); 
    } 
}).send(); 




如果自己定义了回调函数的参数名称. 跟jquery一样.


服务器端你需要这样去取得:


Js代码 
  复制代码 代码如下:


  String callback = request.getParameter("jsoncallback");//取得回调方法名 
        response.setHeader("Cache-Control", "no-cache"); 
        response.setContentType("text/json;charset=UTF-8"); 
        PrintWriter out; 
        try { 
            out = response.getWriter(); 
            out.print(callback+"("+message+")");//这里是关键.主要就是这里 
            out.flush(); 
            out.close(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 




顺便说一句: 个人比较喜欢mootools的语法结构,和框架设计思路. 再次赞美!


Dojo JSONP
JSONP 在Dojo Toolkit 中需要用上dojo.io.script (点击可以查看示例)


 
Js代码 
  复制代码 代码如下:


  // dojo.io.script is an external dependency, so it must be required 
dojo.require("dojo.io.script"); 


// When the resource is ready 
dojo.ready(function() { 


    // Use the get method 
    dojo.io.script.get({ 
        // The URL to get JSON from Twitter 
        url: "", 
        // The callback paramater 
        callbackParamName: "callback", // Twitter requires "callback" 
        // The content to send 
        content: { 
            q: "Arsenal" 
        }, 
        // The success callback 
        load: function(tweetsJson) {  // Twitter sent us information! 
            // Log the result to console for inspection 
            ("Twitter returned: ",tweetsJson); 
        } 
    }); 
}); 
JSONP是一种非常有效的,可靠的,容易实现的远程数据获取方式。JSONP的策略也使开发人员能够避免繁琐的服务器代理方式,很方便的获取数据。

0 0
原创粉丝点击