weixin_33743661 2015-03-24 10:35 采纳率: 0%
浏览 78

如何在Ajax中启用cors?

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:

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:

<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:

[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

   $(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.

thanks in advance for any further feedback/guide.

  • 写回答

2条回答 默认 最新

  • ℡Wang Yan 2015-03-24 11:38
    关注

    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. 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.

    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型