【问题标题】:Ajax only working with certain urlsAjax 仅适用于某些 url
【发布时间】:2017-01-31 21:58:38
【问题描述】:

我在 JavaScript 中有以下代码-#test 是 html 中的简单 h3 标记。我测试这可以用“test1”改变。我的问题是为什么 ajax 只适用于某些 URL。在下面的 sn-p 中,永远不会成功:换句话说,#test 不会变成“test2”。但是,如果我将 URL 替换为

'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1'

成功了。两者都链接到 JSON,对我来说它们看起来一样......那么为什么只有上面显示的 URL 才能成功?

一个类似的问题——jQuery $.ajax not working for a certain URL——说这是由于同源政策。这也适用于我的情况吗?有没有办法解决这个问题?

$(document).ready(function(){
  $("#button").on("click", function(e) {
    e.preventDefault();
    $("#test").html("test1");

    $.ajax({
      url: 'https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=Albert%20Einstein&format=json',
      success: function(data) {
        $('#test').html("test2");

      },
      cache: false
    });
  });
})

【问题讨论】:

  • 这可能是同样的问题。你的控制台日志里写了什么?
  • 另外,请检查开发者控制台的网络选项卡。如果请求成功触发,它应该提供响应。
  • 我使用 CodePen,它什么也没说

标签: javascript php jquery json ajax


【解决方案1】:

找到了一种使用 jsonp 作为数据类型的方法,在这里找到 https://www.mediawiki.org/wiki/Manual:Ajax#Limitations

我更新的代码:

$(document).ready(function(){
  $("#button").on("click", function(e) {
    e.preventDefault();
    $("#test").html($("input").val());
    $.ajax({
      url: "https://en.wikipedia.org/w/api.php?action=query&titles=Boston%20Tea%20Party&prop=revisions&rvprop=content&format=json",
      data: {
        format: 'json' 
      }, 
      dataType: 'jsonp',

      success: function(data) {
        $('#test').html(Object.keys(data.query.pages)[0]);
      },
      cache: false
    });
  });
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2020-10-24
    相关资源
    最近更新 更多