我正在制作一个web应用程序,它根据用户输入HTML表单的城市列出所有的tweet。它从表单的post数据中生成一个$_SESSION['city']变量。
然后,php文件使用会话变量作为查询的参数。这很好,当我导航到tweets.php时,在提交表单后,JSON将成功地从twitter中提取出来。
我想从我的JSON文件name和text中呈现两个字段。我试过使用下面的javascript,但没有效果。有人能告诉我哪里出了问题吗?
$(document).ready(function() {
$.getJSON("http://localhost/Labs/AppName/public/js/tweets.php", function(feeds) {
var feedHTML = "";
for(var i=0; i<feeds.length; i++) {
var tweetname = feeds[i].user.name;
var tweet = feeds[i].text;
feedHTML += "<p>" + tweetname + "<br />" + tweet + "</p>"; //RENDER JSON VARS
}
$("#twitter-feed h3").after(feedHTML);
});
});对该算法的快速总结:
$_POST变量的$_SESSION变量"https://api.twitter.com/1.1/search/tweets.json?q=".$city);中用作参数的会话变量<div id="twitter-feed"> </div>中的HTML附加到tweet中。示例JSON输出(减少):
"created_at":"Wed Feb 04 14:27:27 +0000 2015",
"id":562980760127557633,
"id_str":"562980760127557633",
"text":"http:\/\/t.co\/lbqnmNrHue",
"source":"IFTTT<\/a>",
"truncated":false,
"in_reply_to_status_id":null,
"in_reply_to_status_id_str":null,
"in_reply_to_user_id":null,
"in_reply_to_user_id_str":null,
"in_reply_to_screen_name":null,
"user":{
"id":23638744,
"id_str":"23638744",
"name":"adrian bonnington",
"screen_name":"xymalf",
"location":"UK",
"profile_location":null,
"description":"unemployed electronics engineer.",
"url":"http:\/\/t.co\/XmSePpitdx",
"entities":{
"url":{
"urls":[
{
"url":"http:\/\/t.co\/XmSePpitdx",
"expanded_url":"http:\/\/about.me\/xymalf",
"display_url":"about.me\/xymalf",
"indices":[
0,
22
]
}
]
},
"description":{
"urls":[
]
}
},发布于 2015-02-04 14:31:47
这样的ajax函数可以做出您想要的相同的更改。
$.ajax({
url: '/Labs/AppName/public/js/tweets.php',
type: 'post',
data:{'city':city},
dataType: 'json',
timeout: 20000,
tryCount: 0,
retryLimit: 3,
success: function(feeds) {
$.each(feeds.length, function(k, each_user) {
feedHTML += "<p>" + each_user.name + "<br />" + each_user.text + "</p>";
});
$("#twitter-feed h3").after(feedHTML);
}
})发布于 2015-02-04 14:46:00
JSON作为ajax的响应值,在大多数情况下需要转换为JavaScript对象。在那之后,一切都很简单。只需对对象数组进行迭代,并按照您的习惯使用它们。如果响应是字符串,则向下运行代码,否则检查JSON验证http://jsonlint.com/
$(document).ready(function() {
$.getJSON("http://localhost/Labs/AppName/public/js/tweets.php", function(feeds) {
var feed = JSON.parse(feeds); //Java script object
var feedHTML = "";
for(var i=0; i<feeds.length; i++) {
feedHTML += "<p>" + feeds[i].user.name + "<br />" + feeds[i].text + "</p>";
}
$("#twitter-feed h3").after(feedHTML);
});
});https://stackoverflow.com/questions/28323673
复制相似问题