以下是完整的错误消息:
XMLHttpRequest无法加载http://api.nytimes.com/svc/search/v2/articesearch.json?q=&sort=newest&api-key=APIKEY_HERE。 No' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' null'因此不允许访问。响应的HTTP状态代码为404.
我正在尝试使用NY Times API根据页面输入搜索文章。这是我的javascript:
function loadData() {
var $body = $('body');
var $wikiElem = $('#wikipedia-links');
var $nytHeaderElem = $('#nytimes-header');
var $nytElem = $('#nytimes-articles');
var $greeting = $('#greeting');
$wikiElem.text("");
$nytElem.text("");
var streetStr = $("#street").val();
var cityStr = $("#city").val();
var address = streetStr + ", " + cityStr;
$greeting.text('So you want to live at ' + address + '?');
var streetViewURL = 'http://maps.googleapis.com/maps/api/streetview?size=600x300&location='+ address + '';
$("body").append('<img class="bgimg" src="'+streetViewURL+'">');
var nytimesUrl = 'http://api.nytimes.com/svc/search/v2/articesearch.json?q=' + cityStr + '&sort=newest&api-key=APIKEY_HERE';
$.getJSON(nytimesUrl, function(data){
nytHeaderElem.text("New York Times Articles About "+cityStr);
articles = data.response.docs;
for(var i = 0;i<articles.length;i++){
var article = articles[i];
nytElem.append('<li class="article">'+'<a
href="'+article.web_url+'">'+article.headline.main+'</a>'+'<p>' +article.snippet+'</p>'+'</li>');
};
});
return false;
};
$('#form-container').submit(loadData);
我的HTML是
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Your Moving Companion</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!-- index.html file -->
<form id="form-container" class="form-container">
<label for="street">Street: </label><input type="text" id="street" value="">
<label for="city">City: </label><input type="text" id="city" value="">
<button id="submit-btn">Submit</button>
</form>
<hr>
<h2 id="greeting" class="greeting">Where do you want to live?</h2>
<div class="wikipedia-container">
<h3 id="wikipedia-header">Relevant Wikipedia Links</h3>
<ul id="wikipedia-links">Type in an address above and find relevant Wikipedia articles here!</ul>
</div>
<div class="nytimes-container">
<h3 id="nytimes-header">New York Times Articles</h3>
<ul id="nytimes-articles" class="article-list">What's going on in your new city? Enter an address and hit submit and the NY Times will tell you here!</ul>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"
integrity="sha256-/SIrNqv8h6QGKDuNoLGA4iret+kyesCkHGzVUUV0shc="
crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/file.js"></script>
</body>
</html>
感谢您的帮助
答案 0 :(得分:0)
看起来像是一个Cross Origin Issue,尝试在你的http请求标题中添加这一行,让我们知道它的工作正常与否。
标题:{&#39;内容类型&#39;:&#39; application / x-www-form-urlencoded&#39;, &#39; X-Requested-With&#39;:&#39; XMLHttpRequest&#39;}