jquery - 启用Web服务的跨域访问

标签 jquery asp.net cross-domain cross-domain-policy

我想让 Web 服务能够被任何域访问,所以我研究了以下内容
clientaccesspolicy.xml

<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="*">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>


crossdomain.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<?xml version="1.0" ?>
<cross-domain-policy>
  <allow-http-request-headers-from domain="*" headers="SOAPAction,Content-Type"/>
  <allow-access-from domain="*" />
</cross-domain-policy>


在我的 web.config 中,我添加了以下内容

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol> 

我已经一一使用了这两个文件,并且同时使用了这两个文件。仍然无法从其他域请求。
这是jquery代码

           var cid="My String Input";
           var webMethod = "MyWemMethodUrl";
           var parameters = "{'ContactID':'" + cid + "'}";

           $.ajax({
               type: "POST",
               url: webMethod,
               data: parameters,
               async: false,
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               success: function (result) {
                   debugger;
                   var _JSONObj = jQuery.parseJSON(result.d);
                   if (_JSONObj.StatusCode == "0") {
                       alert("Error");
                   }
                   else {
                       alert("Success");
                   }
               },
               error: function (jqXHR, exception, thrownError) {
                   debugger;
                   if (jqXHR.status === 0) {
                       alert('Not connected.\nPlease verify your network connection.');
                   } else if (jqXHR.status == 404) {
                       alert('The requested page not found. [404]');
                   } else if (jqXHR.status == 500) {
                       alert('Internal Server Error [500].');
                   } else if (exception === 'parsererror') {
                       alert('Requested JSON parse failed.');
                   } else if (exception === 'timeout') {
                       alert('Time out error.');
                   } else if (exception === 'abort') {
                       alert('Ajax request aborted.');
                   } else {
                       alert('Uncaught Error.\n' + jqXHR.responseText);
                   }
               }
           });

它总是出现 jqXHR.status=0 路径错误
即使我尝试了 dataType: "jsonp"而不是 dataType: "json"。
这是我的控制台屏幕 来自 Chrome 浏览器 enter image description here




enter image description here

最佳答案

好吧,我终于发现我的代码出了什么问题。
我在 javascript Ajax 调用中的 url 中添加回调并将数据类型值设置为 jsonp


        $.ajax({
        type: "POST",
        url: WebMethod+'?callback=jsonCallback',
        crossDomain: true,
        contentType: "application/json; charset=utf-8",    
        data: parameters,
        dataType: "jsonp",
        jsonpCallback: 'jsonCallback',
        success: function (result) {
             /*SUCCESS CODE*/
        },
        error: function (jqXHR, exception, thrownError) {

           /*error Code*/
        }

});


我用 void 更改为非返回类型,而不是字符串返回类型函数。

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
 public void WebMethod()
    {
       String ReponseResult = "";/*Json String that i want to return*/
        /*My Code and logic

           ----

         */
    /*To return Json String  I added following Code*/
  try
    {


        string callback = HttpContext.Current.Request.Params["callback"];
        string json = ReponseResult;
        string response1 = string.IsNullOrEmpty(callback) ? json : string.Format("{0}({1});", callback, json);

        // Response
        HttpContext.Current.Response.ContentType = "application/json";
        HttpContext.Current.Response.Write(response1);
    }
    catch (Exception ex) { }
    }


关于jquery - 启用Web服务的跨域访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25890247/

相关文章:

jquery - 浏览器警报样式

javascript - 当多个 Magento 扩展包含 Jquery 库时怎么办

security - 单页 Web 应用程序、CORS 和安全问题

asp.net - 带有FormsAuthentication的跨域Cookie

jquery - 防止日期选择器触发父鼠标离开

Javascript将变量连接到url

asp.net - JavaScript 没有按预期工作,为什么?

javascript - 使用 jQuery javascript 根据域显示内容

c# - 如何在asp.net中的PostBack页面中接收值?

c# - 高效的批量数据插入