跨域访问(ajax+nginx)

1.配置nginx的location
列如:

location /onePriceLog {
        index  index.html;
            proxy_pass http://192.168.128.110:81/admin/trans/onePriceLog.f;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        client_max_body_size    10m;
        proxy_redirect off;
        }

2.写ajax,这里提供一个原生态的封装

var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for Firefox, Opera, IE7, etc.
  xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
  xmlhttp.onreadystatechange=state_Change;
  xmlhttp.open("POST",url,true);
  xmlhttp.send("");
  }
else
  {
  alert("Your browser does not support XMLHTTP.");
  }
}

function state_Change()
{
if (xmlhttp.readyState==4)
  {// 4 = "loaded"
  if (xmlhttp.status==200)
    {// 200 = "OK",业务



    }
  else
    {
    //alert("Problem retrieving data:" + xmlhttp.statusText);
    }
  }
}

3.调用封装函数

loadXMLDoc("/onePriceLog?transTargetId="+pageObj.targetId);

这里做一下简单说明,比如我们在A程序(无法修改其代码,只能修改页面,因为程序不是我们开发的,拿不到源代码,哈哈,所以只能苦逼的修改页面)里面请求另外一个程序B(这个是小猿开发的)里面的内容,请求列如是http://221.224.76.18:8089/admin/trans/onePriceLog.f,这个时候如果直接在A页面加载请求就会发生跨域问题,如果是通过nginx就很巧妙的把http://221.224.76.18:8089/admin/trans/onePriceLog.f这个请求转化成B程序的**/onePriceLog请求。就可以避免跨域访问。相当于把A和B的域合成一个C域,这样就不存在跨域问题了。
http://221.224.76.18:8089/admin/trans/onePriceLog.f=/onePriceLog
“`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值