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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵