我在从链接获取返回的数据时遇到问题。它不起作用。 我进行了更多搜索并尝试了所有方法,但它仍然不起作用。谁能帮助我。 链接:https://www.routingnumbers.info/api/data.json?rn=13442323 我的代码是
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var request = $.ajax({
type: 'GET',
data: "rn=" + "54455445",
url: "https://www.routingnumbers.info/api/data.json",
success: function(data) {
alert("Data: " + data + "\nStatusA: " + status);
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Data: " + "Err" + "\nStatus: " + status);
console.log(jqXHR, textStatus, errorThrown);
request.abort();
}
});
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
谢谢
最佳答案
首先,我总是建议在 ajax 请求中使用正确的 JSON 格式。数据属性应该是一个对象而不是变量赋值。到最后,这实际上并不重要;请求将以任一格式完成。不过,查看格式一致的代码总是好的。无论如何,导致请求失败的主要问题是您发出的请求的类型及其来源。
在您提供的代码中,您向 https
地址发出请求。但是,您请求的页面不是 https
页面,而是 http
页面。这导致请求返回错误 net::ERR_INSECURE_RESPONSE
。
但是,如果您解决了这个问题,请求仍然无法成功完成。这是因为 XMLHttpRequest 不允许向与您发出请求的网站不同的网站发出请求。例如,如果您从 routingnumbers.info
内部运行脚本,则可以从 routingnumbers.info
请求内容,但如果您从其他地方运行脚本,则不能请求内容。可以通过将请求指定为 jsonp
请求而不是默认的 json
请求来解决此问题。
$("button").click(function(){
$.ajax({
type: "GET",
dataType: "jsonp",
async: true,
url: "http://www.routingnumbers.info/api/data.json",
data: {
rn: "54455445"
},
success: function(data) {
var array = [];
$.each(data, function(index, value){
array.push(index + ': ' + value);
});
alert(array.join("\n"));
},
error: function(data) {
alert(data.statusText);
}
});
});
希望这对您有帮助!
关于javascript - 使用 javascript/Jquery 进行 Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29200792/