我正在使用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对象的某些部分,并将它们分开放置。
任何帮助都将深表感谢!
答案 0 :(得分:0)
您可以使用.
“运算符”来访问JSON对象中的某些键。
在您的情况下,假设您在名为var
的{{1}}中保存了JSON,quote
将等于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;
答案 1 :(得分:0)
由于您要以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>