我向Twitter API提出了请求。如何从我的PHP脚本获取JSON响应到我的JavaScript?

时间:2014-04-02 17:52:44

标签: javascript php json twitter

我正在做一个Twitter API请求,它返回包含#awkward的所有推文的JSON。以下是服务器上的成功响应:http://babbage.cs.missouri.edu/~atgvyc/php/election_tweets/index.php

但我希望能够在我的JavaScript中使用该JSON并通过for循环解析它以获取某些信息(特别是地理标记和位置)。我以为我可以用AJAX和JSON.parse做到这一点,但它没有像我想象的那样工作。

有什么建议吗?

这是我的PHP脚本:

<?php
require_once('TwitterAPIExchange.php');

$settings = array(
'oauth_access_token' => "XXX",
'oauth_access_token_secret' => "XXX",
'consumer_key' => "XXX",
'consumer_secret' => "XXX"
);

$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=#awkward&geocode=38.949926,-92.330037,35mi&result_type=recent';
$requestMethod = 'GET';

$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
         ->buildOauth($url, $requestMethod)
         ->performRequest();
?>  

这是我的HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Sample elections tweets</title>

    <script>
    function loadXMLDoc()
    {
        var xmlhttp;

        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
        }

        else
        {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {   
                var json = JSON.parse(xmlhttp.responseText);

                //here's where i'd like to put a for-loop
            }
        }

        xmlhttp.open("GET","index.php",true);
        xmlhttp.send(); 
    }
    </script>
</head>
<body>
    <h2>AJAX</h2>
    <button type="button" onclick="loadXMLDoc()">Request data</button>
<body>

1 个答案:

答案 0 :(得分:1)

好的,我想我知道你现在要做什么。确实没有开箱即用的“for each”,就像在php中一样,这就是为什么很多框架都有自己的实现(jQuery的$ .each()),或者做原型。但是,您可以通过以下方式完成所需的操作。如果需要,你可以用alert()替换所有的console.log(),但是它不会出现在Chrome的开发工具(大多数机器上的f12)中。另外,如果Dale Musser还在那里告诉他你好! MIZ

function loadXMLDoc()
{
    var xmlhttp;

    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }

    else
    {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {   
            var json = JSON.parse(xmlhttp.responseText);

            //log entire json struct to developer console for easy viewing
            console.log(json);

            //you can reference individual pieces of json by doing something like
            //json.statuses or json.statuses[2]
            var statuses = json.statuses;

            for(var i=0;i<statuses.length;i++){
                var curStatus = statuses[i];

                //access bits directly
                var tweetAuthor = curStatus.user.name;
                var tweetTime = curStatus.created_at;

                //iterate hashtags
                var hashtags = curStatus.entities.hashtags;
                for(var k=0;k<hashtags.length;k++){
                        console.log("Hashtag: " + hashtags[k].text);
                }

                //iterate all elements of tweet
                for(var key in curStatus){

                    var attrName = key;
                    var attrValue = curStatus[key];

                    console.log("attribute name: " + attrName);
                    console.log("attribute key: " + attrValue);
                    if(attrName = "text") {
                        //Do something with tweet texts... like: 
                        //document.getElementById("statuses").appendChild(attrValue);
                    }
                }
            }

        }
    }

    xmlhttp.open("GET","index.php",true);
    xmlhttp.send(); 
}