Muh*_*tar 3 html javascript asp.net jquery web-services
我试图调用外部Web服务,它在chrome中工作正常,但在firefox和IE中却没有.在chrome中,它返回'true',但在firefox中,它返回'0 error',这里是我的完整代码...
<script type="text/javascript" src="js/jquery-1.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnCall").click(function (event) {
var campaignid = 1000007;
var r_source_id = 1000008;
var parameters = "{'CompanyName': '" + document.getElementById('txtCompanyName').value + "', 'name': '" + document.getElementById('txtName').value + "', 'title': '', 'email':'" + document.getElementById('txtEmail').value + "', 'phone':'" + document.getElementById('txtPhoneNo').value + "', 'web_url':'', 'no_of_emp':'0', 'c_Currency_id':'100', 'r_source_id':'" + r_source_id.toString() + "', 'industry_ID':'1', 'city':'', 'country_ID':'" + document.getElementById('ddlCountry').value + "', 'cur_solution':'','pur_timeline':'','comments':'', 'year_sell_erp':'2013', 'support':'', 'bpgroup_ID':'1', 'C_Campaign_ID':'" + campaignid.toString() + "', 'R_STATUS_ID':'1000033', 'C_Region_ID':'100', 'CreatedBy':'1000012', 'salesrep_id':'1000012', 'ad_org_id':'1000001', 'ad_client_id':'1000001', 'UpdatedBy':'100', 'AccessKey':'caff4eb4fbd6273e37e8a325e19f0991'}";
$.ajax({
type: "POST",
url: "http://cloudservice.softwareonthecloud.com/service.asmx/SetLead",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
});
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
</script>
Run Code Online (Sandbox Code Playgroud)
这是我上传此功能URL进行测试
您收到此错误,因为您尝试在另一个域上调用Web服务.这违反了同源政策.这是一个安全限制.大多数旧版浏览器都会拒绝此类请求.
如果要在javascript中访问webservice的其他域,则需要设置 跨源资源共享.
跨源资源共享(CORS)是一种允许网页将XMLHttpRequests发送到另一个域的机制.根据相同的原始安全策略,Web浏览器将禁止此类"跨域"请求.CORS定义了浏览器和服务器可以交互以确定是否允许跨源请求的方式
如果您可以访问Web服务代码,则可以在服务器上启用CORS请求.
启用cors是一个很好的资源.这是对科尔的一些解释
在IIS 7上,您需要在web.config中设置一些自定义标头.
<system.webserver>
<httpprotocol>
<customheaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customheaders>
</httpprotocol>
</system.webserver>
Run Code Online (Sandbox Code Playgroud)
安全注意:这里有一个例子,我已经允许所有对服务器的请求.如果您要提供敏感数据,则可能需要将此限制为选定的域.
基于WCF的请求也可以通过检查,WebOperationContext.Current.IncomingRequest并且可以发送适当的头.
旧版浏览器不支持CORS请求.您可以在此处查看完整的浏览器兼容性列表
如果您必须支持旧版浏览器,或者无法更改Web服务,则可以始终在服务器上托管Web服务代理.您将请求发送到您的服务器,您的服务器请求原始webserivce中的数据.这样可以正常工作,因为它不违反交叉原始政策.一个简单的http处理程序可以作为服务器上的代理服务器.
以下是REST Web服务的示例http处理程序代理:
public void ProcessRequest(HttpContext context) {
WebClient myClient = new WebClient();
//Fetch response on your server
string response = myClient.DownloadString("http://example.com/webservice/webMethod");
// Send response to your javascript.
context.Response.Write(response);
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以根据需要从javascript调用此处理程序.
| 归档时间: |
|
| 查看次数: |
5955 次 |
| 最近记录: |