【问题标题】:My API URL is Correct and the HTTP(S) is Correct, but Console.log() Comes up Blank? Why?我的 API URL 正确且 HTTP(S) 正确,但 Console.log() 显示为空白?为什么?
【发布时间】:2018-06-16 10:45:21
【问题描述】:

我无法使用任何 API 网址!我所有的 JavaScript 代码都是正确的,所以我不知道问题出在哪里。

我的 CodePen 控制台和 Google Chrome 开发者控制台是空白的! 在此处查看屏幕截图:https://s25.postimg.org/k5ds4p1xb/Console_Test.jpg (Screenshot of consoles)

这是我的 CodePen: https://codepen.io/IDCoder/full/KZqNdr/

这是我的 JavaScript 代码:

$(document).ready(function(){

  var quote;

  function getNewQuote() {
    $.ajax({
      url: 'https://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&jsonp=?',
      jsonp: 'jsonp',
      dataType: 'jsonp',
      data: {
        method: 'getQuote',
        lang: 'en',
        format: 'jsonp'
      },
      success: function(response) {
        //quote = response.quoteText;
        console.log(response.quoteText);


      }
    });
  }
  //getNewQuote();
});

 //getNewQuote();

 // $('.get-quote').on('click', function(e) {
  //  e.preventDefault();
   // getNewQuote();
  //});

  //$('#quote').text(response.quoteText);
        //if (response.quoteAuthor) {
          //$('#author').text('said by ' + response.quoteAuthor);
        //} else {
         // $('#author').text('- unknown');
        //}

评论者建议我使用 ajax 错误调用,我实现了该调用并让 Google Chrome 开发人员控制台记录此 “加载失败https://codepen.io/boomerang/iFrameKey-a33d8144-0d32-5d95-7476-4d00493149e7/wrongfile.txt:对预检请求的响应未通过访问控制检查:否'Access-Control-Allow-Origin' 标头出现在请求的资源上。因此,不允许访问 Origin 'https://s.codepen.io'。响应的 HTTP 状态代码为 404。” ....我很困惑!

【问题讨论】:

  • 嗯...你考虑过添加错误处理程序吗?
  • 阅读$.ajax的文档
  • 是的....没错。但是请注意,jsonp 请求实际上是脚本请求。错误处理不如常规 ajax 强大
  • 需要添加简单的错误回调函数w3schools.com/jquery/…
  • 你试过了吗?

标签: javascript ajax api jsonp access-control


【解决方案1】:

在 codepen 上将协议更改为 https 并取消注释 getNewQuote();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2021-07-13
    • 2023-01-13
    • 1970-01-01
    • 2016-09-16
    相关资源
    最近更新 更多