jsonpクロスドメイン要求struts 2データ取得
2781 ワード
安全のために、jsは国境を越えて訪問してはいけません.しかし、時にはこの方面の需要があります.一般的な解決方法はScriptタグを動的に作成し、戻るjs方法を実行します.
jsコード:
jsコード:
<%@ page language="java" import="java.util.*" pageEncoding="gb18030"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>jsonp-test</title>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<script type="text/javascript">
function show(text){
document.getElementById("t").innerHTML = text;
}
function getData(){
var script=document.createElement("script");
var s = document.getElementById("s").value;
s = s==""? "127.0.0.1:8080":s;
script.src = "http://" + s + "/jsonpTest/jsonp.action?callback=show";
document.getElementsByTagName("head")[0].appendChild(script)
}
</script>
</head>
<body>
<div>
<div>
( ):<input type="text" value="" id="s" >
</div>
<div><input type="button" value=" " onclick="getData()" /> </div>
<div style="background: teal;width:500px;height:300px" >
:
<div id="t" style="color: red" ></div>
</div>
</div>
</body>
</html>
javaコード:package com.ldl.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
public class JsonpAction {
public String jsonp(){
try {
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
String callback = request.getParameter("callback");
String returnResult = "";
if(callback != null && !"".equals(callback)){
returnResult = callback + "(\" jsonp \")";
}
response.setCharacterEncoding("gb18030");
response.setContentType("text/javascript");
PrintWriter writer = response.getWriter();
writer.println(returnResult);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}