【问题标题】:Unable to get JSON response form Ajax request无法从 Ajax 请求中获取 JSON 响应
【发布时间】:2021-02-07 18:46:18
【问题描述】:

我有 Json 格式的 WordPress 提要 (https://blog.piscessportfishing.com/feed/json/),但我无法使用 ajax 请求来阅读它。 成功我没有得到任何数据变量。相反,它会在警报中给出错误。

这是我的代码:

$.ajax({
    type: 'GET',       
    url: "https://blog.piscessportfishing.com/feed/json/",
    dataType: 'json',
    data: {},
    success: function(data) {
        console.log(data);            
    },
    error: function (Request, textStatus, errorThrown) {
        alert("Request=" + Request.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
    }        
  });

【问题讨论】:

  • 您是否有任何CORS错误,这意味着您无法访问其他域URL?仅供参考,您应该为所有类型的请求添加标头,它应该是一个正确的结构
  • @HemaRamasamy 是的,问题出在 CORS 上,感谢您的帮助。

标签: jquery json ajax


【解决方案1】:

错误:

从源“http://XYZ”访问“https://blog.piscessportfishing.com/feed/json/”的 XMLHttpRequest 已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头存在于请求的资源上。

使用它在您的 WordPress 网站上启用 CORS: 在您的 functions.php 文件中添加以下代码。

header( 'Access-Control-Allow-Origin: ' . esc_url_raw( site_url() ) );

文档:https://developer.mozilla.org/fr/docs/Web/HTTP/CORS

【讨论】:

  • 谢谢@Yvan1263 问题出在 CORS 上,我在 function.php 文件中添加了以下代码,它起作用了。 ` function add_cors_http_header(){ header("Access-Control-Allow-Origin: *"); } add_action('init','add_cors_http_header'); `
猜你喜欢
  • 2018-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 1970-01-01
相关资源
最近更新 更多