【问题标题】:Error in CORS ajax requestCORS ajax 请求中的错误
【发布时间】:2014-05-26 19:36:49
【问题描述】:

在 php 我做echo json_encode($dump);

如果使用 php 回显它,我会得到 {"load":"0.64 0.58 0.52 2\/361 12978\n","procs":"8\n"}

比我使用 dataType:jsonp 发出 CORS 请求

$(function () {
    $.ajax({
        type: "POST",
        ContentType: 'application/json; charset=utf-8',
        url: 'http://labs.isaumya.com/loadtest/load',
        dataType: "jsonp",
        success: function (response) {
            console.log(response.data);
        },
        error: function (xhr, status, error) {
            console.log(error);
        }
    });
});

我在控制台上收到此错误:

DEMO

【问题讨论】:

  • 在jsonp的情况下你需要使用回调作为响应。

标签: php jquery json jsonp cors


【解决方案1】:

您正在处理 JSON,而不是 JSONP。 dataType: "jsonp", 应该是 dataType: "json",

如果您的服务器为 JSON (application/json) 输出正确的内容类型标头,则您可以完全删除 data 参数。


JSONP 是一种在浏览器设计和实现 CORS 之前解决同源策略的 hack。 CORS 是提出跨源请求的现代方法。您使用它而不是 JSONP。


CORS 和 JSONP 都是服务器必须支持的技术。 http://labs.isaumya.com/loadtest/load 似乎也不支持。如果您希望服务器以 JSONP 格式提供数据或通过 CORS 授予权限,则必须修改服务器。


与您的实际问题无关:

您没有data 参数,因此您没有将JSON 发送到 到服务器,请删除ContentType 参数。由于您没有发布任何数据,因此您可能应该发出 GET 请求,而不是 POST 请求。

【讨论】:

  • 如果我使用json,它将无法满足CORS 请求。
  • @user3527203 — CORS 是 JSONP 的现代替代方案。您不会将 JSONP 用于 CORS 请求。
  • 查看 --> jsfiddle.net/w7D5V/2 我做了你说的更改,但仍然出现错误XMLHttpRequest cannot load http://labs.isaumya.com/loadtest/load. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access. (index):1
  • 如答案中所述:“如果您希望服务器以 JSONP 格式提供数据或授予 CORS 权限,则必须修改服务器”
猜你喜欢
  • 2021-11-02
  • 2017-04-21
  • 2023-03-21
  • 1970-01-01
  • 2022-01-21
  • 2021-06-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-15
相关资源
最近更新 更多