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.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#wireshark#的问题:并且能够给数据做标注,如这个流量是在看视频或者是在转账
  • ¥90 请问,这个视频播放软件的名称,用过的朋友请给答案,上方..avi是啥意思?是看短剧还是播放本地视频?
  • ¥15 运筹优化,gurobi,python
  • ¥15 基于python的电影系统推荐
  • ¥20 springmvc重定向和返回json
  • ¥15 数学建模——参会安排怎么做
  • ¥15 电脑键盘实现触摸功能
  • ¥25 matlab无法将表达式转换为双数组怎么解决?
  • ¥15 单片机汇编语言相关程序
  • ¥20 家用射频美容仪技术规格