【问题标题】:Jquery ajax call getting error in external url in mvcJquery ajax 调用在 mvc 的外部 url 中出现错误
【发布时间】:2015-08-10 01:06:36
【问题描述】:

当给定外部 url 以获取结果时,我在 jquery ajax 调用中遇到错误。网址在 mvc Dot net 中

 var url = "http://demo.bucesoft.com/BUCESFTDETAILS/insertrecrd";
         $.ajax({
             url: url,
             contentType: "application/json; charset=utf-8",
             datatype: "json",
             data: "{'obj':'" + Senddetails + "'}",
             type: "POST", // 'GET' or 'POST' ('GET' is the default)
             success: function (data) {
                 alert('sucess');
                 console.log(data);

             },
             error: function (xhr, status, error) {
                 var err = eval("(" + xhr.responseText + ")");
                 alert(err.Message);
             }
         });

在这我得到错误

XMLHttpRequest cannot load http://demo.bucesoft.com/BUCESFTDETAILS/insertrecrd. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

请帮帮我

【问题讨论】:

    标签: jquery ajax model-view-controller


    【解决方案1】:

    您必须启用 CORS 才能启用跨域请求。

    要启用 CORS 支持,请将 Microsoft.AspNet.WebApi.Cors NuGet 包添加到您的项目中。

    将此代码添加到您的配置中:

    public static void Register(HttpConfiguration config)
    {
        // New code config.EnableCors();
    }
    

    要启用跨域请求,请将 [EnableCors] 属性添加到您的 Web API 控制器或控制器方法:

    [EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
    public class TestController : ApiController 
    {
        // Controller methods not shown...
    }
    

    在 PHP 中,您可以通过设置自定义标头来允许,如下所示。

    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
    

    您还可以通过定义名称来启用该特定站点,例如

    header("Access-Control-Allow-Origin: http://yourdomainname.com/");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-30
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      相关资源
      最近更新 更多