我输了:-(我通过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');
}
});
});
除“成功”之外,每个警报都有效。 '完成'后我可以做任何我想做的事。如何让结构随时可用于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的一部分,或至少解析,以便我可以利用这些字段?
答案 0 :(得分:0)
使用JSON.parse()
将JSON格式的字符串转换为对象:
success: function(posts) {
someVariable = JSON.parse(posts);
}
如果您的成功回调没有解雇,那么您还有另一个问题。错误的输出是什么?
error: function(jqXhr, status, errorThrown) {
console.log(jqXhr);
console.log(status);
console.log(errorThrown);
}
答案 1 :(得分:0)
它正在发送SUCCESS,因为您要求它被警告。为了迭代JSON,JSON可以存储在一个变量中,因为你已经有了posts
,你可以使用它在success函数中使用循环进行迭代,如下所示:
for(var i=0;i<posts.length;i++){
alert(posts[i].author);
alert(posts[i].body);
//Etc. Other fields can be well added.
}