简体   繁体   English

如何在Ajax中启用cors?

[英]How enable cors in ajax?

I am trying to call data from the following host url test.domain.com/test2.aspx/BindDatatable , however i keep getting 404 response and the following message in my console window: 我正在尝试从以下主机URL test.domain.com/test2.aspx/BindDatatable调用数据,但是我在控制台窗口中test.domain.com/test2.aspx/BindDatatable收到404响应和以下消息:

error message: 错误信息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://test.domain.com/test2.aspx. This can be fixed by moving the resource to the same domain or enabling CORS

i have added the following cors header in the web.config file of my host(url ) file: 我在host(url)文件的web.config文件中添加了以下cors标头:

<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="origin" />
<add name="Access-Control-Request-Method" value="POST" /> 
<add name="Access-Control-Allow-Headers" value="content-type, accept" /> 
</customHeaders>
</httpProtocol>
</system.webServer>

it also contains the following web-method behind test2.aspx.cs: 它还在test2.aspx.cs后面包含以下Web方法:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod()]
public static string BindDatatable()
{
    DataTable dt = new DataTable();
    List<UserDetails> details = new List<UserDetails>();

    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["#####"].ConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand("######", con))
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            foreach (DataRow dtrow in dt.Rows)
            {
                UserDetails user = new UserDetails();
                user.Name= dtrow["###"].ToString();
                user.Loan = dtrow["###"].ToString();
                user.Evnt = dtrow["###"].ToString();
                details.Add(user);
            }
        }
    }
     JavaScriptSerializer serializer = new JavaScriptSerializer();
     return serializer.Serialize(details);
}

ajax function called from corsTest.aspx 从corsTest.aspx调用的ajax函数

   $(document).ready(function () {
    $.support.cors = true;
    $.ajax({
        type: "Post",
        crossDomain: true,
        contentType: "application/json; charset=utf-8",
        url: "http://wwww.test.domain.com/test2.aspx/BindDatatable",
        data: "{}",
        dataType: "json",
        success: function (data) {
            alert(data.toSource());
            console.log(data);
            var myData = JSON.parse(data.d)
             for (var i = 0; i < myData.length; i++) {
                 $("#tbDetails").append("<tr><td>" + myData[i].Name + "</td><td>" + myData[i].Loan + "</td><td>" + myData[i].Evnt + "</td></tr>");                    
            }
        },
        error: function (result) {
            alert("Error");
        }
    });
});

I am not sure, what else i am suppose to update further to get this to work. 我不确定,我还要进一步更新以使其正常工作。 Do I also need, to define the cors header in the head tag of the text2.aspx page as well. 我还需要在text2.aspx页面的head标签中定义cors标头吗?

thanks in advance for any further feedback/guide. 在此先感谢您提供任何其他反馈/指南。

I stuck into similar situation today so sharing my solution, hope it could help somebody. 我今天遇到了类似情况,因此分享我的解决方案,希望它可以对某人有所帮助。 I used jsonp to fetch the data from cross domain. 我使用jsonp从跨域获取数据。 Taking your example, if one has access to BindDatatable() method in test2.aspx.cs , then we can modify json object to be returned in the format like jsonData({..your json..}) . 以你的例子,如果一个人有获得BindDatatable()方法test2.aspx.cs ,那么我们可以通过修改JSON对象到像格式返回jsonData({..your json..}) By wrapping the method with jsonData(), it could be read by jsonp during ajax call made like: 通过用jsonData()包装该方法,可以在进行如下ajax调用时由jsonp读取它:

var url = "http://wwww.test.domain.com/test2.aspx/BindDatatable";
    $.ajax({
                url: url,
                dataType: 'jsonp',
                jsonpCallback: 'jsonData',
                success: function (response) {
                    console.log('callback success: ', response);
                },
                error: function (xhr, status, error) {
                    console.log(status + '; ' + error);
                }
            });

Otherwise as suggested in the above post, you can create a function in your own application corsTest.aspx.cs and access cross domain link through it in C# and return json as shown below: 否则,如上述文章中所建议,您可以在自己的应用程序corsTest.aspx.cs创建一个函数,并在C#中通过它访问跨域链接并返回json,如下所示:

$.ajax({
    type: "Post",
    contentType: "application/json; charset=utf-8",
    url: "/corsTest.aspx/BindDatatableTest",
    dataType: "json",
    .
    .
    error: function (result) {
        alert("Error");
    }
});

Define function in corsTest.aspx.cs like: 在corsTest.aspx.cs中定义函数,如下所示:

private string BindDatatableTest()
{
    JavaScriptSerializer serializer = new JavaScriptSerializer(); 
    string url = "http://wwww.test.domain.com/test2.aspx/BindDatatable";
    WebClient wc = new WebClient();        
    ServicePointManager.Expect100Continue = false;
    ServicePointManager.MaxServicePointIdleTime = 2000;
    string json = wc.DownloadString(url);
    object jsonData = new
    {
          jsonFinal = jsonD
    };

    return Content(serializer.Serialize(jsonData), "application/json");
}

Also, in order to call cross domain url you have to add the following code to web.config: 另外,为了调用跨域网址,您必须将以下代码添加到web.config中:

<system.net>
    <settings>
      <httpWebRequest useUnsafeHeaderParsing="true" />
    </settings>
  </system.net>

Check if the remote method is available. 检查远程方法是否可用。 Check the firewall of the server where the service is hosted if it allows connections for the specific port. 如果服务允许特定端口的连接,请检查托管该服务的服务器的防火墙。 Also check on your machine if output port is not blocked. 同时检查计算机上的输出端口是否未阻塞。

Another way to enable cors is to make the connection on the server side. 启用cors的另一种方法是在服务器端进行连接。 For instance you can add service reference to the remote method and use that method on the server side in your local project. 例如,您可以将服务引用添加到远程方法,并在本地项目的服务器端使用该方法。 Then on the client you have to call only the local method that is within your solution and you don't have to enable cors on the client. 然后,在客户端上,您仅需要调用解决方案中的本地方法,而无需在客户端上启用cors。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM