码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA与AJAX跨域执行

时间:2015-05-12 11:37:56      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:javascript   ajax   jsonp   

问题来源:一个jsp页面上有个链接需要访问第三方接口,第三方并返回数据给我。

问题思路:首先思考的就是使用AJAX异步方式将他所需的数据给第三方接口,第三方接口返回一系列参数,并根据SUCCESS参数,在页面上弹框显示。

过程解析:页面上写完整AJAX返回JSON数据发现不管怎么样都执行error,经过一系列的查找找到问题所在为AJAX跨域获取数据只能用JSONP,(伤心,看了API才明白是怎么回事),贴下代码:

JSP页面:

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<script type="text/javascript" src="common/jquery-1.6.min.js"></script>
	<script type="text/javascript" >
  	function insert(){
		$.ajax({
			type:"GET",
			url:"http://10.40.114.59:8090/test/test.action",
			dataType:"jsonp",
			jsonp:"callbackParam",
 			jsonpCallback:"success_jsonCallback",
			success:function(json){
				alert(json);
				alert("success");
			},
			error:function(){
				alert("error");
			}		
		});
  	}
  </script>
  </head>
  
  <body>
    <br/>
    <input type="button" value="测试" onclick="insert()"/>
  </body>
  
  
</html>

Servlet代码:

<servlet>
  	<servlet-name>test</servlet-name>
  	<servlet-class>test.ReceiveformAction</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>test</servlet-name>
  	<url-pattern>*.action</url-pattern>
  </servlet-mapping>

JAVA代码:

package test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

public class ReceiveformAction extends HttpServlet{
	
	public void doGet(HttpServletRequest request,HttpServletResponse response) {
		
		try {
			
			PrintWriter out = response.getWriter();
			String callbackName = request.getParameter("callbackParam");
			HashMap<String,String> hMap = new HashMap<String,String>();
			hMap.put("success", "true");
			out.write(callbackName+"("+JSONObject.valueToString(hMap).toString()+")");
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	}

}

抓包截图:

技术分享

返回数据:

 

技术分享

 


 

 


 

 

 

 

 

JAVA与AJAX跨域执行

标签:javascript   ajax   jsonp   

原文地址:http://blog.csdn.net/lyy176/article/details/45646163

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!