我使用的是一个API (https://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?),它为我提供了这个对象(作者随机引用):
?({"quoteText":"Life is so constructed that an event does not, cannot, will not, match the expectation. ","quoteAuthor":"Charlotte Bronte","senderName":"","senderLink":"","quoteLink":"http://forismatic.com/en/16af75b8b4/"})我将如何将Life is so constructed that an event does not, cannot, will not, match the expectation.与"quoteText":隔离开来,并将其放在HTML代码中的某个地方。
隔离也是一样的:Charlotte Bronte与"quoteAuthor":并将其放在我的HTML代码中。加分,有时"quoteAuthor":字段留空,不知道发生时该做什么。
我知道如何将整个JSON对象放在我的HTML代码中,我只需要一些帮助来隔离JSON对象的某些部分,并将它们分开放置。
任何帮助都将不胜感激!
发布于 2017-06-15 20:01:23
因为您是以JSONp格式检索,所以请记住,您需要将dataType设置为jsonp,以便jQuery能够正确地解析它。这样做之后,在jqXHR.done回调中,您可以只访问实际的JSON响应。
您所收到的只是一个对象,它包含键值对格式的数据。为了访问这个值,比如Life is so constructed that...,您必须通过它的键(即quoteText )来检索它。使用点表示法并假设对象存储在一个变量中,比如response,那么可以使用response.quoteText访问引用。见以下概念证明示例:
$(function() {
var request = $.ajax({
url: 'https://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?',
dataType: 'jsonp'});
request.done(function(response) {
// 'response' is the entire JSON returned
console.log(response.quoteText);
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
发布于 2017-06-15 14:48:33
您可以使用.“运算符”从JSON对象访问某些键。
在您的例子中,假设您在一个名为var的quote中保存了JSON,quote.quoteText将等于"Life is so constructed that an event does not, cannot, will not, match the expectation. "
var quote = {"quoteText":"Life is so constructed that an event does not, cannot, will not, match the expectation. ","quoteAuthor":"Charlotte Bronte","senderName":"","senderLink":"","quoteLink":"http://forismatic.com/en/16af75b8b4/"};
document.querySelector("#div").innerHTML = quote.quoteText;
document.querySelector("#from").innerHTML = quote.quoteAuthor;Quote:
<pre id="div"></pre>
From: <span id="from"></span>
你应该调查一下W3学校的JSON教程
https://stackoverflow.com/questions/44570382
复制相似问题