ajax跨域请求

什么是跨域

JavaScript出于安全方面的考虑,不允许跨域调用其他页面的对象。但在安全限制的同时也给注入iframe或是ajax应用上带来了不少麻烦。首先什么是跨域,简单地理解就是因为JavaScript同源策略的限制,a.com 域名下的js无法操作b.com或是c.a.com域名下的对象。

function refreshDict(){
$.ajax({
type: "POST",
async: false,
cache : false,
url: "${appPath}/admin/dict/refreshDict.do",
dataType: "text",
success: function(data){
if(data == "success"){
msg = msg +"管理端刷新<span style='color:green;'><b>成功</b></span>";
}else{
msg = msg +"管理端刷新<span style='color:red;'><b>失败</b></span>";
}
},
error : function() {
msg = msg +"管理端刷新<span style='color:red;'><b>异常</b></span>";
}
});
msg += "<br>";

<c:forEach items="${interface_addr_list}" var="v" >
alert('${dValue}');
</c:forEach>

$.ajax({
type: "get",
async: false,
cache : false,
dataType:"jsonp",/*加上datatype*/
url: "http://192.168.1.253:8080/mobile2/refreshDict.json?jsoncallback=callback"
});

}

//callback方法名是固定的

function callback(data) {
if(data.code == "success"){
msg = msg +"接口服务端刷新<span style='color:green;'><b>成功</b></span>";
}else{
msg = msg +"接口服务端刷新<span style='color:red;'><b>失败</b></span>";
}
layer.alert(msg);
msg = "";
}

后台接口服务要返回内容类似如下:

String callbackName = request.getParameter("jsoncallback");

return callbackName+"({"code":"SUCCESS"})";

不想用ajax跨域也可以用后台请求:

public class HttpRequestUtil {

    
    /**
     * 发送Http post请求
     * @param reqUrl
     * @param data
     * @return
     */
    public static String doHttpPost(String reqUrl, String data) {
       byte[] xmlData = null;
       if(data != null){
           xmlData = data.getBytes();
       }
        InputStream instr = null;
        //java.io.ByteArrayOutputStream out = null;
        try {
            URL url = new URL(reqUrl);
            URLConnection urlCon = url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setRequestProperty("content-Type", "application/json");
            urlCon.setRequestProperty("charset", "utf-8");
            //urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            if(xmlData != null){
                printout.write(xmlData);
            }
            printout.flush();
            printout.close();
            instr = urlCon.getInputStream();
            byte[] bis = IOUtils.toByteArray(instr);
            String ResponseString = new String(bis, "UTF-8");
            /*if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
               BaseConstant.MY_LOG.info("返回空");
            }*/
            BaseConstant.MY_LOG.info("返回数据为:" + ResponseString);
            return ResponseString;
        } catch (Exception e) {
            e.printStackTrace();
            return "-1";
        } finally {
            try {
                /*if(out != null){
                    out.close();
                }*/
                if(instr != null){
                    instr.close();
                }
            } catch (Exception ex) {
                return "-1";
            }
        }
    }
    
    public static void main(String[] args) {
        doHttpPost("http://192.168.1.254:8080/mobile2/refreshDict.json", null);
    }
}
public static String doHttpPost(String reqUrl) {
         InputStream instr = null;
         String result = null;
         try {
             URL url = new URL(reqUrl);
             URLConnection urlCon = url.openConnection();
             //获取响应码
             /*HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(reqUrl).openConnection();
             httpURLConnection.setRequestMethod("POST");
             int status = httpURLConnection.getResponseCode();
             httpURLConnection.disconnect();
             BaseConstant.MY_LOG.debug(status);*/
             urlCon.setDoOutput(true);
             urlCon.setDoInput(true);
             urlCon.setUseCaches(false);
             urlCon.setRequestProperty("content-Type", "application/json");
             urlCon.setRequestProperty("charset", "utf-8");
             DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
             printout.flush();
             printout.close();
             instr = urlCon.getInputStream();
             result = IOUtils.toString(instr, StandardCharsets.UTF_8);
             /*byte[] bis = IOUtils.toByteArray(instr);
             return result = new String(bis, "UTF-8");*/
             return result;
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             try {
                 if(instr != null){
                     instr.close();
                 }
             } catch (Exception ex) {
                 BaseConstant.MY_LOG.error("InputStream关闭异常" + ex);
             }
         }
         return result;
     }
     
原文地址:https://www.cnblogs.com/shihaiming/p/5959562.html