jquery - 在 ajax 中发布时出现 Access-Control-Allow-Origin 错误

标签 jquery ajax

$.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'https://your_url.aspx', // the url where we want to POST
        data        : school, // our data object
        dataType    : 'json', // what type of data do we expect back from the server
                    encode          : true
    })
        // using the done promise callback
        .done(function(data) {

            // log data to the console so we can see
            console.log(data); 

            // here we will handle errors and validation messages
        });

    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();

这是我的代码,用于将一些表单数据发布到特定的网址,但我收到以下错误:

POST https://your_url.aspx 500 (Internal Server Error)
send @ jquery-3.2.1.min.js:4
ajax @ jquery-3.2.1.min.js:4
(anonymous) @ magic.js:20
dispatch @ jquery-3.2.1.min.js:3
q.handle @ jquery-3.2.1.min.js:3
index.html:1 XMLHttpRequest cannot load 
https://your_url.aspx. No 'Access-Control-
Allow-Origin' header is present on the requested resource. Origin 'null' is 
therefore not allowed access. The response had HTTP status code 500.

我四处寻找如何允许 access-control-allow-origin 并在 $.ajax 中使用

beforeSend: function(request){
  request.setHeaderRequest("Access-Control-Allow-Origin","*")
}

后来在 stackoverflow 中看到更多响应后,我将 setHeaderRequest 更改为 addHeaderReuest,但即便如此,尽管错误已被删除,但我也没有看到来自服务器的响应。控制台显示为空白。

如有任何帮助,我们将不胜感激。

最佳答案

出现此错误是因为您试图从您的域访问另一个域。使用同源策略,我们只能请求同一域中存在的那些网址。在我们获得另一个站点的身份验证之前,浏览器不允许跨域请求(通常称为CORS)。 Access-Control-Allow-Origin 响应 header 指示是否可以与具有给定源的资源共享响应。查看文档Access-Control-Allow-Origin

关于jquery - 在 ajax 中发布时出现 Access-Control-Allow-Origin 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45396976/

相关文章:

javascript - 如何仅在单击表头时在表头上应用样式并在单击任何其他表头时删除样式?

c# - asp mvc格式时间跨度(mm :ss) textboxfor to work with bootstrap timepicker

javascript - Mongodb 将变量设置为 find().toarray()

javascript - HTML JavaScript - 带有额外/可选字段的表单问题

javascript - 防止 JQuery .HTML 在显示之前覆盖以前的 .HTML

php - responseText 包含额外的空白字符(换行,换行),如何防止和删除它们?

javascript - 如何防止 Focus() 方法将页面滚动到顶部

javascript - 使用 Javascript 中的 api 调用将图像 url 获取到 HTML 中的图像标记?

jQuery:按下回车键时显示的内容

javascript - 使用 jQuery(或不使用)的简单 AJAX POST 请求提交表单