我迷路了 :-( 我通过 CORS 收到了来自 AJAX 请求的成功响应,但我不知道如何实际使用我获取的 JSON 文件。
我所有的警报都有效。如何将接收到的 JSON 文件缓存为函数/变量?
$(function(){
var pulseRestApiGetQueryUri = "https://doesntmatter/api/v1/search.json?q=" + encodeURIComponent("%23c2alerts");
$.support.cors = true;
$.ajax({
type: "GET",
headers: {'X-API-Key': 'com.amazon.c2alerts'},
url: pulseRestApiGetQueryUri,
timeout: 10000, // 10 seconds
contentType: "application/json; charset=utf-8",
dataType: "json",
xhrFields: {withCredentials: true},
success: function(posts) {
alert('SUCCESS');
},
error: function(jqXhr, status, errorThrown) {
alert('ERROR');
},
beforeSend: function() {
alert('BUSY');
},
complete: function() {
alert('COMPLETE');
}
});
});
除“SUCCESS”外,每个警报都有效。“完成”后我可以做任何我想做的事。如何使结构易于用于 HTML 操作,我应该把它放在哪里?
这是我的 JSON 中的两个示例条目。
{
"author":{
"namespace":"user",
"name":"nichazel",
"string_form":"user:nichazel",
"full_name":"Nicholas Hazel"
},
"body":"Have an idea? We are trying to collect new and fresh ideas for process improvement. Please jot down ANY ideas you may have. We will discuss them in our team meeting this afternoon -urgent #c2alerts",
"topics":[
{
"namespace":"hashtag",
"name":"c2alerts",
"string_form":"hashtag:c2alerts"
}
],
"source":"web",
"post_id":"30d97e00-596f-4936-ade9-557db0e907df",
"created":"2013-07-31T20:18:22Z",
"votes":{
"up_votes":2,
"down_votes":0,
"up_voters":[
{
"namespace":"user",
"name":"bostrom",
"string_form":"user:bostrom"
},
{
"namespace":"user",
"name":"eakerry",
"string_form":"user:eakerry"
}
],
"down_voters":[
]
}
},
{
"author":{
"namespace":"user",
"name":"chayavic",
"string_form":"user:chayavic",
"full_name":"Sam Chayavichitsilp"
},
"body":"Happy Friday C2. Retail AHOD (L2) - No Stand-Up Meeting for the entire team.\n#c2alerts",
"topics":[
{
"namespace":"hashtag",
"name":"c2alerts",
"string_form":"hashtag:c2alerts"
}
],
"source":"web",
"post_id":"a05d96ae-2c6e-4054-989f-d25a74bfc553",
"created":"2013-07-26T14:57:18Z"
},
这是一个通过 getJSON 工作的示例(我不能使用它,因为它不是 CORS):
$.getJSON('jsonURL',function(data){
$.each(data.results, function(i, item) {
alert(item.body);
});
});
相同的原则不适用于常规 AJAX 请求。任何想法如何将 JSON 作为 DOM 的一部分,或者至少被解析以便我可以利用这些字段?