如何解决此错误

How can i resolve this error

本文关键字:错误 解决 何解决      更新时间:2023-09-26

我正在尝试使用AJAX调用WCF服务,下面是我的代码:

$.ajax({
    url: "http://localhost/TestingServices/Service1.svc/GetData"
    data: "{'value:1}",
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        alert(data);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert(textStatus);
    }
});

但在执行后,它给了我以下错误:

XMLHttpRequest cannot load 
  http://localhost/TestingServices/Service1.svc/GetData.Response to 
  preflight request doesn't pass access control check: 
  No 'Access-Control-Allow-Origin' header is present on 
  the requested resource. Origin 'null' is therefore not 
  allowed access. The response had HTTP status code 404.

有人能帮我解决这个问题吗?

尝试在服务项目的web.config中添加2个HttpProtocols

    <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

请尝试这个。。。。

$.ajax({
type: "GET",
url: "http://localhost/TestingServices/Service1.svc/GetData",
dataType: "jsonp",
success: readData(data),
error: function (xhr, ajaxOptions, thrownError) {
  alert(xhr.status);
  alert(thrownError);
 }
})