简体   繁体   中英

I made a request to the Twitter API. How can I get the JSON response from my PHP script to my JavaScript?

I'm doing a Twitter API request that returns JSON of all tweets containing #awkward . Here's the successful response on a server: http://babbage.cs.missouri.edu/~atgvyc/php/election_tweets/index.php

But I want to be able to use that JSON in my JavaScript and parse through it with a for-loop to pull out certain information (particularly the geotags and location). I thought I could do this with AJAX and then JSON.parse, but it's not working the way I thought it would.

Any suggestions?

Here's my PHP script:

<?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();
?>  

Here's my 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>

Ok, I think I know what you are trying to do now. There really isn't an out of the box "for each" like there is in php, which is why a lot of frameworks implement there own (jQuery's $.each()), or make prototypes. But, you may be able to do what you need with the below. You can replace all the console.log() with alert() if you want, but it gets hectic not being in Chrome's dev tools (f12 on most machines). Also, if Dale Musser is still there tell him hello! 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(); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM