Nea*_*alR 4 c# ajax jquery xmlhttprequest cross-domain
我对Ajax比较陌生,只是负责这个跨域调用.我们的网页上有一个文本框,用户可以用它来预先搜索公司名称.通过单击文本框旁边的按钮,将请求Ajax调用.遗憾的是,Web服务位于一个单独的域中,因此这自然会导致问题.
以下是我做这项工作的最佳尝试.我还应该注意,此调用的目的是以XML格式返回结果,该格式将success在请求的部分中进行解析.
这是错误消息:
Origin http://localhost:55152 is not allowed by Access-Control-Allow-Origin.
我不知道如何处理解决方案,任何想法都会受到高度赞赏.
function GetProgramDetails() {
var URL = "http://quahildy01/xRMDRMA02/xrmservices/2011/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,\'" + $('.searchbox').val() + "\')";
var request = $.ajax({
type: 'POST',
url: URL,
contentType: "application/x-www-form-urlencoded",
crossDomain: true,
dataType: XMLHttpRequest,
success: function (data) {
console.log(data);
alert(data);
},
error: function (data) {
console.log(data);
alert("Unable to process your resquest at this time.");
}
});
}
Run Code Online (Sandbox Code Playgroud)
此错误是由于跨域资源共享中强制实施的限制.这已作为安全功能的一部分实现,以通过跨域调用限制资源的客户端(域).当您向webservice或api或类似服务器发送请求时,它会在服务器或目标服务器(此处为您的api)的请求中添加Origin标头,以验证请求是否来自授权来源.理想情况下,API /服务器应该寻找Origin在Request header收到,可能验证对集,它允许将资源用于起源(域)的.如果它来自允许的域,它将在响应头中添加相同的域作为"Access-Control-Allow-Origin"值.也允许使用通配符,但问题在于,通过外卡允许,任何人都可以发出请求并获得服务(有一些限制,例如api通过Windows身份验证或cookie进行身份验证,您需要发送withCredentials值*不允许).使用通配符来源响应标头并不是一个好习惯,它使每个人都可以使用它.
以下是使用值设置响应标头的一些方法: -
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: http://yourdomain.com
Run Code Online (Sandbox Code Playgroud)
你甚至可以在同一个响应中添加多个Access-Control-Allow-Origin标头(我相信在大多数浏览器中都有效)
Access-Control-Allow-Origin: http://yourdomain1.com
Access-Control-Allow-Origin: http://yourdomain2.com
Access-Control-Allow-Origin: http://yourdomain3.com
Run Code Online (Sandbox Code Playgroud)
在服务器端(c#语法)你会这样做: -
var sourceDomain = Request.Headers["Origin"]; //This gives the origin domain for the request
Response.AppendHeader("Access-Control-Allow-Origin", sourceDomain ); //Set the response header with the origin value after validation (if any) .Depending on the type of application you are using syntax may vary.
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!!!
| 归档时间: |
|
| 查看次数: |
10651 次 |
| 最近记录: |