JAVA中AJAX用JSONP方案实现跨域
前端AJAX请求
dataType为jsonp
增加参数 jsonpCallback
值为回调函数,需自己用js实现
<script type="text/javascript" >
var openurl="http://www.abc.cn/Test2";
$.ajax({
type: "get",
dataType: "jsonp",
url: openurl,
jsonpCallback:"showData",
async: false,
error:function(E){
alert( "return1: " + E );},
success: function(msg){
}
});
function showData(msg){
var result = JSON.stringify(msg);
alert(result);
$("#a").text(msg.nickname);
}
</script>
后端java代码,响应内容需用回调函数名包含
如,回调函数为showData
响应内容为"showData("+userinfo+")"
package weixin;
import java.io.PrintWriter;
import javax.servlet.ServletException;
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 TestServlet2 extends HttpServlet {
public void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,java.io.IOException
{
response.setContentType("text/html;charset=utf-8");
PrintWriter out= response.getWriter();
String userinfo = "{ 'openid':' OPENID',"+
"'nickname': '路飞',"+
"'sex':'1',"+
"'province':'PROVINCE',"+
"'city':'CITY',"+
"'country':'COUNTRY'"+
"}";
try {
JSONObject json= new JSONObject(userinfo);
out.println("showData("+userinfo+")");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}