Ajax仅适用于某些URL [英] Ajax only working with certain urls

查看:106
本文介绍了Ajax仅适用于某些URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中有以下代码-#test是html中的简单h3标签.我测试可以使用"test1"更改它.我的问题是为什么ajax仅适用于某些URL.在以下代码段中,永远不会达到成功:换句话说,#test不会成为"test2".但是,如果我将URL替换为

I have the following code in JavaScript- #test is a simple h3 tag in html. I test that this can be changed with "test1". My question is why ajax will only work with certain URLs. In the following snippet, the success is never reached: in other words, #test does not become "test2". However, if I replace the URL with

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

成功.两者都链接到JSON,对我来说它们看起来相同...那么为什么仅对上面显示的URL成功?

success IS reached. Both link to JSON, and they look the same to me... so why is success only reached for the URL shown above?

一个类似的问题- jQuery $ .ajax不适用于特定网址-表示这是由于相同的原始政策所致.这也适用于我的情况吗?有什么办法可以解决这个问题?

A similar question-- jQuery $.ajax not working for a certain URL --says that this is due to the same origin policy. Does this apply to my case as well? Is there any way to get around this?

$(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
    });
  });
})

推荐答案

找到了一种使用jsonp作为数据类型的方法,可在此处找到

Found a way around using jsonp as the data type, found here 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
    });
  });
})

这篇关于Ajax仅适用于某些URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆