【发布时间】:2014-03-07 03:42:19
【问题描述】:
我正在尝试使用 jQuery 来利用 Glosbe.com/a-api 上的 Web 服务。谁能告诉我为什么我下面的代码没有返回任何结果?我希望在 Glosbe 上用一个词查询 API,并在下面显示该词的定义。
谢谢。
这是我拥有的 jQuery:
$(document).ready(function(){
$('#term').focus(function(){
var full = $("#poster").has("img").length ? true : false;
if(full === false){
$('#poster').empty();
}
});
var getPoster = function(){
var film = $('#term').val();
if(film === ''){
$('#poster').html("<h2 class='loading'>Ha! We haven't forgotten to validate the form! Please enter something.</h2>");
} else {
$('#poster').html("<h2 class='loading'>Your definition is on its way!</h2>");
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=hello&pretty=true" + film + "?callback=?", function(json) {
if (json !== "Nothing found."){
$('#poster').html('<h2 class="loading">Well, gee whiz! We found you a definition, skip!</h2><img id="thePoster" src=' + json[0].posters[0].image.url + ' />');
} else {
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=hello&pretty=true" + "?callback=?", function(json) {
console.log(json);
$('#poster').html('<h2 class="loading">Nothing found.</h2><img id="thePoster" src=' + json[0].posters[0].image.url + ' />');
});
}
});
}
return false;
};
$('#search').click(getPoster);
$('#term').keyup(function(event){
if(event.keyCode === 13){
getPoster();
}
});
});
还有 HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="author" content="Matthew Hughes">
<meta name="Dictionary" content="A dictionary web service">
<title>Dictionary Web Application</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<!--jQuery, linked from a CDN-->
<script src="dictionary.js"></script>
<script type="text/javascript" src="http://use.typekit.com/oya4cmx.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<header>
<h1>Dictionary Application</h1>
</header>
<section id="fetch">
<input type="text" placeholder="Enter a word..." id="term" />
<button id="search">Define!</button>
</section>
<section id="poster">
</section>
<footer>
<p>Created by Matthew Hughes</p>
</footer>
</div>
</body>
谢谢。
【问题讨论】:
-
您正在尝试跨域请求。 See this comment
标签: javascript jquery json api