我是新来的使用JavaScript,所以请原谅我不好的术语。jQuery返回的数据不整洁
我有一个jQuery调用词典Web服务的API,整个函数按原样工作(返回所有定义,作者等)。
但我的问题是,从API返回的数据返回到一个大的文本块,而不是以每个定义之间的行间距的整齐格式。
如果我只是在网络浏览器中搜索URL,我会收到一个json响应,其中包含整洁的定义和间距。
这是我在服务中搜索API和返回的数据。
这里只是利用我的代码的URL通过Web浏览器(我怎么觉得应该看在我的web服务返回时)搜索
有没有人曾经之前看过这个问题,或者知道为什么,从我的代码中,它是这样做的!
任何帮助将不胜感激!
$(document).ready(function(){
$('#term').focus(function(){
var full = $("#definition").has("definition").length ? true : false;
if(full === false){
$('#definition').empty();
}
});
var getDefinition = function(){
var word = $('#term').val();
if(word === ''){
$('#definition').html("<h2 class='loading'>We haven't forgotten to validate the form! Please enter a word.</h2>");
}
else {
$('#definition').html("<h2 class='loading'>Your definition is on its way!</h2>");
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=&pretty=true" +word+ "?callback=?", function(json) {
if (json !== "No definition has been found."){
var reply = JSON.stringify(json,null,"\t");
var n = reply.indexOf("meanings");
var sub = reply.substring(n+8,reply.length);
var subn = sub.indexOf("]");
sub = sub.substring(0,subn);
$('#definition').html('<h2 class="loading">We found you a definition!</h2><h3>'+sub+'</h3>');
}
else {
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=&pretty=true" + "?callback=?", function(json) {
console.log(json);
$('#definition').html('<h2 class="loading">Nothing found.</h2><img id="thedefinition" src=' + json.definition[0].image.url + ' />');
});
}
});
}
return false;
};
$('#search').click(getDefinition);
$('#term').keyup(function(event){
if(event.keyCode === 13){
getDefinition();
}
});
});
和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>
<script src="dictionary.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<div id="top">
<header>
<h1>Dictionary Application</h1>
</header>
</div>
<div id="app">
<input type="text" placeholder="Enter a word..." id="term" />
<button id="search">Define!</button>
<section id="definition">
</section>
</div>
<footer>
<p>Created by Matthew Hughes</p>
</footer>
</div>
</body>
您的浏览器正在添加换行符。 JSON没有格式。 –
无论如何将链接中断添加到我在javascript中返回的数据? – omgched
原始的JSON有换行符,但是您调用'$ .getJSON'。将JSON解析为一个Javascript对象,这只是数据。然后你调用'JSON.stringify',它产生一个无格式的JSON字符串。 – Barmar