Ajax – Access-Control-Allow-Origin不允许使用Origin localhost

我对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."); } }); } 

此错误是由于跨域资源共享中强制实施的限制。 这已作为安全function的一部分实现,以通过跨域调用限制资源的客户端(域)。 当您向webservice或api或类似设备发送请求时,它会在服务器或目标请求(此处为您的api)中添加Origin标头,以validation请求是否来自授权来源。 理想情况下,api / server应该在它收到的Request header查找Origin ,并且可能根据允许为其提供资源的源(域)集进行validation。 如果它来自允许的域,它将在响应头中添加与"Access-Control-Allow-Origin"值相同的域。 也允许使用通配符,但问题在于,通过外卡允许,任何人都可以发出请求并获得服务(有一些限制,例如api通过Windows身份validation或cookie,您需要发送withCredentials*身份validation不允许)。 使用通配符来源响应标头并不是一个好习惯,它使每个人都可以使用它。

以下是使用值设置响应标头的一些方法: –

 Access-Control-Allow-Origin: * Access-Control-Allow-Origin: http://yourdomain.com 

你甚至可以在同一个响应中添加多个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 

在服务器端(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. 

希望这可以帮助!!!