html中怎么跨域访问

什么是跨域访问,就是我的网站要用你网站的资源

当然我们可以用html发送请求我们网站的后台,通过后台的httpurlconnection去操作其他网站的资源

但是假如我没有后台 页面时静态的只是和com对象交互怎么办了

首先我们可以使用jquery

首先在js开头 导入jquery

{
 var jquerjs = document.createElement('script');
 jquerjs.id='jquerjs';
 jquerjs.type='text/javascript';
 jquerjs.encoding='utf-8';
 jquerjs.src = "jquery-1.4.2.js";
 if (document.body != null)
    document.body.appendChild(js);
}

比如通过用户名去取一个xml字符串

function toGetPolicy(userId){
       var url=g_bdpsvr +"userReg/getPolicy.do?userId="+userId;
    $.ajaxSettings.async = false;
    $.ajaxSetup({
         async: false
        });
       $.ajax({
            type : "GET",
            url : url,
            dataType : "script",
            async : false,
            success : function(json){
    policyXml=msg;
    hooksubmit();
            }
        });
 
}

 dataType : "script",
表示是用去获取一个javascript  javascript是可以跨域去取的 所以我们在后台用java生成一个方法(这里是用struts2)

public String toGetPolicy() {

  String userId = ServletActionContext.getRequest()
    .getParameter("userId");
  ClientService service = (ClientService) DlpContext
    .getApplicationContext().getBean("clientService");
  String xml = service.getPolicy(userId, null);
  xml=xml.replaceAll("////", "////////");
  ServletActionContext.getResponse().setContentType("text/html; charset=utf-8");
  try {
   ServletActionContext.getResponse().getWriter().print("var msg='"+xml+"';");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }

ServletActionContext.getResponse().getWriter().print("var msg='"+xml+"';");

表示获取到了一个变量 var msg=想要的字符串

我们就一再jquery的回调函数中使用 msg变量了

当然 jquery者玩意本来就是用js实现的我们同样可以不用jquery 我们用javascript

var g_bdpsvr=http://192.168.3.4:8080/abc

function toTGetPolicy(userId){
       var url=g_bdpsvr +"userReg/getPolicy.do?userId="+userId;
    var dataoldjs=document.getElementById("jquerjs");
    if(dataoldjs!=null)
            document.body.removeChild(dataoldjs);
    var datajs = document.createElement('script');
    datajs.id='jquerjs';
    datajs.type='text/javascript';
    datajs.encoding='utf-8';
    datajs.src = url;
    datajs.onreadystatechange = function(){  
   var state = datajs.readyState;
   if (state == "loaded" || state == "interactive" || state == "complete") { 
     try{
     policyXml=msg;
     }catch(e){};
   }  
       }
    if(document.body != null)
    document.body.appendChild(datajs);

    document.body.removeChild(datajs);

}

其实jquery就是这么实现的 效果是一样 同样或以获取到msg变量

原文地址:https://www.cnblogs.com/liaomin416100569/p/9331550.html