日期:2014-05-16  浏览次数:20376 次

关于javascript访问Webservice跨域问题
一、开发环境:Asp.net 2008 

二、问题描述:
  使用基础的xmlHttpRequest访问Webservice,此Webservice是基于.net的用IIS发布的。如果使用基础xmlHttpRequest的AJax访问localhost的webservice可以访问到。 
  例如:
  var _webserviceUrl='http://localhost/DemoWebservice/DemoService.asmx';
  var xhr= new window.XMLHttpRequest();
  xhr.open("POST", _webserviceUrl, false);
  ……
  xhr.send(_data);
  可以正常的访问到
   
  但是将localhost换成本机的IP地址,如:192.168.0.201,运行到 xhr.send()方法时就报:“拒绝访问”。更不用说局域网内的其他机器了。
  后来搜索了一下,好像是js跨域的问题。

三、现在的疑问:
  遇到这种js跨域访问webservice有什么解决方法呢? 
  好像看到一种是使用 代理 的方式来解决的,请问具体如何操作呢? 实在不了解。 请哪位明白人指教下,讲解一下具体的思路,可以的话给点关键性的代码、或者是相关网站。


  十分感谢您的关注和帮助。
   
 

------解决方案--------------------
only to be reference------------------------------
protected void Page_Load(object sender, EventArgs e)
{
if (Request["WEB"] != null)
{
Response.Clear();
//Response.AppendHeader("Content-type", "text/xml;charset=GB2312");
System.Net.HttpWebResponse rs = (System.Net.HttpWebResponse)System.Net.HttpWebRequest.Create(Request["WEB"]).GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(rs.GetResponseStream(), System.Text.Encoding.Default);
Response.Write(sr.ReadToEnd());
Response.End();
}
}
Default.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>通过JS获取异步数据</title>

<script language="javascript" type="text/javascript">
var xmlHttp=null;
var xmlDom =null;
var xslDom =null;

function send()
{
xmlHttp=new ActiveXObject("MSXML2.XMLHTTP");
xmlDom =new ActiveXObject("MSXML2.DOMDocument");

//xmlHttp.onreadystatechange=doHttpReadyStateChange;
xmlHttp.open("POST","/XmlHttp/GetData.aspx?WEB=http://www.163.com",false);
xmlHttp.send("");
result=xmlHttp.responseText;
//alert(result);
// xmlDom.loadXML(result);
// items1=xmlDom.selectNodes("//NewDataSet/FriendLink/vc_LinkName");
// alert(items1.length);
// for(i=0;i<items1.length;i++)
// {
// TextArea1.value+=items1(i).text;
// }
document.write(xmlHttp.responseText);
}

function doHttpReadyStateChange()
{
if(xmlHttp.readyState==4)
{
TextArea1.value+=xmlHttp.responseText;
}
}
</script>

</head>
<body>
<input id="Button1" type="button" value="提交" onclick="send();" />
<br />
<br />
<br />
<textarea id="TextArea1" style="width: 925px; height: 441px"></textarea>
</body>
</html>


------解决方案--------------------
强悍,纯粹帮顶
------解决方案--------------------
just for reference
Javascript跨域访问解决方案
http://blog.csdn.net/lovingprince/archive/2008/09/20/2954675