AJAX 请求在家里工作但不在我的学校

AJAX requests are working at home but not at my school

不知道是我的代码有问题还是我学校的网络有问题。在家里代码 'works'(我的意思是至少显示来自 api 的信息)但在学校我什么也得不到。这也是我的 codepen。感谢您的帮助!

$(document).ready(function() {
  $("#searchBtn").click(function() {
    var $theData = $("#theData");
    $.ajax({
      url: 'http://en.wikipedia.org/w/api.php',
      data: {
        action: 'opensearch',
        limit: 10,
        namespace: 0,
        search: $("#search").val(),
        format: 'json'
      },
      dataType: 'jsonp',
      success: function processResult(apiResult) {
        var html = "";
        $.each(apiResult, function(i, apiResult) {
          var keys = Object.keys(apiResult);
          html += "<div>";
          keys.forEach(function(key) {
            html += "<strong>" + key + "</strong>: " + apiResult[key] + "<br>";
          });
          html += "</div><br>";
        });
        $theData.html(html);
        console.log(JSON.stringify(apiResult));
        console.log(html);
      }
    });
  });
});

它会起作用,但您正在跨越 HTTP 和 HTTPS。

当您 运行 从 HTTPS 网站访问时,您将无法 post 访问 HTTP 网站。更多信息:https://developers.google.com/web/fundamentals/security/prevent-mixed-content/what-is-mixed-content

将您的 JS 代码中的 URL 更改为 https,它应该可以工作。

下次,查看开发人员工具栏,您应该会看到错误消息,其中解释了我在这里所做的事情;

Mixed Content: The page at 'https://codepenDOTio/johnthorlby/pen/RoJKVz' was loaded over HTTPS, but requested an insecure script 'http://en.wikipedia.org/w/api.php?callback=jQuery3100(...)ction=opensearch&limit=10&namespace=0&search=hodor&format=json&_=1481621576214'. This request has been blocked; the content must be served over HTTPS.

你的学校似乎正在封锁 https://cdnjs.cloudflare.com

您可以尝试使用其他 CDN,例如https://developers.google.com/speed/libraries/#jquery.