我正在尝试从 javascript 调用 Web 服务。在 Internet Explorer 9 中正常工作,而 chrome 不工作。错误如下:
“OPTIONS http://www.restfulwebservices.net/wcf/CurrencyService.svc?wsdl 400(错误请求)XMLHttpRequest 无法加载http://www.restfulwebservices.net/wcf/CurrencyService.svc?wsdl。不允许使用 Origin null通过访问控制允许来源。”
我留下代码来帮助我。谢谢。` 函数 SOAPClient() { this.wsdl = ''; this.async = true; this.action = ''; this.xml = '';
SOAPClient.prototype.invoke = function(){
var xhr;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
} else {// code for IE6, IE5
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange=function() {
if (xhr.readyState >= 3){
alert ('ReadyState '+xhr.readyState+' - - Status '+xhr.status);
if(xhr.status == 200)
document.getElementById("txtResult").innerHTML=xhr.responseText;
else
document.getElementById("txtResult").innerHTML='Error';
}
}
xhr.open("POST", this.wsdl,this.async);
xhr.setRequestHeader("SOAPAction", this.action);
xhr.setRequestHeader("Content-Type", "text/xml");
xhr.setRequestHeader("Connection", "close");
xhr.send(this.xml);
return false;
}
}
</script>
<script type="text/javascript">
var wsdl = 'http://www.restfulwebservices.net/wcf/CurrencyService.svc?wsdl';
var action = 'GetConversionRate';
var xml = '';
var async = true;
var response = '';
function prueba(){
var client = new SOAPClient();
client.wsdl = wsdl;
client.action = action;
client.xml = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.restfulwebservices.net/ServiceContracts/2008/01"><soapenv:Header/><soapenv:Body><ns:GetConversionRate><ns:FromCurrency>EUR</ns:FromCurrency><ns:ToCurrency>GBP</ns:ToCurrency></ns:GetConversionRate></soapenv:Body></soapenv:Envelope>';
client.invoke();
return false;
}
</script>
</head>
<body>
<p>Versión 2.5</p>
<form name="form" action="#">
Term: <input type="text" name="inputValue" method="post"/>
<button onclick="prueba()">Search</button>
<p id="txtResult"></p>
</form>
</body>
`