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);
                }
            );  


 

posted @ 2018-04-25 10:30  super超人  阅读(7985)  评论(0编辑  收藏  举报