doubengshao8872 2019-06-20 04:05
浏览 94

在页面加载后更新在PHP中完成的Web服务调用的最佳方法

I have a webpage that uses PHP to make a REST API call and returns an JSON array used later in the page. This php is meant to run on loading (yes, I understand php is ran server side), but it performs the API default request automatically upon loading the page.

I have an input group that is meant to change the query parameters of the API request which in turn updates the array that is being manipulated later.

I would assume that updating query parameters on the fly is a fairly common thing to be done - but the only way I can think to do it in my scenario is by calling my php to do it with the new parameters.

This brings up 2 problems: 1 If I put the API call php code within a function, and try to call it with some ajax, it doesn't execute the default query on load. 2 If the api call is not in a function, I don't know how to call it again when I have updated parameters from my input group.

The API call:

    <?php

    $include = '';
    $exclude = '';

    $url = "https://api.twitter.com/1.1/tweets/search/30day/dev30.json";
        $requestMethod = "GET";
        if (isset($_GET['topic']))  {$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['topic']);}  else {$user  = "@avaya";}
        //if (isset($_GET['count']) && is_numeric($_GET['count'])) {$count = $_GET['count'];} else {$count = 6;}


        $getfield = "?query=$user+$include+$exclude";


        $twitter = new TwitterAPIExchange($settings);
        $string = json_decode($twitter->setGetfield($getfield)
        ->buildOauth($url, $requestMethod)
        ->performRequest(),$assoc = TRUE);
        if(array_key_exists("errors", $string)) {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}


        $id_array = array();

        //Foreach loop to create divs

        foreach ($string['results'] as $tweets)
        {


          $id_array[] = $tweets['id_str'];


        }
    ?>

$id_array is used later in javascript as it is set to var jsarray = <?php echo json_encode($id_array); ?>;

Code for my input group to get new parameters:

                    <div class="input-group">
                <div class="input-group-prepend"><span class="input-group-text">Exclude</span></div><input id="input-exclude" class="form-control" type="text">
                <div class="input-group-append"><button onclick="getExclude()" class="btn btn-primary" type="button">Go</button></div>
                <script>
                function getExclude()
                {
                  var toExclude = document.getElementById('input-exclude').value;
                  console.log("getExclude() has been called");
                  console.log("You requested to exclude: " + toExclude);

                  excludeString = excludeString + "&"

                  //excluded =
                }

                <?php
                  if(isset($_COOKIE['include']))
                  {
                    $include = $_COOKIE['include'];
                  }
                ?>

                </script>
            </div>

This is just for the include portion of the problem - exclude is identical, just different on the API side so I left it out.

At this point I would like re-run the php bit with the updated value for $include. As mentioned earlier - I have tried put all of that php code in a function, like this:

                           function callTwitter(){
        $url = "https://api.twitter.com/1.1/tweets/search/30day/dev30.json";
        $requestMethod = "GET";
        if (isset($_GET['topic']))  {$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['topic']);}  else {$user  = "@avaya";}
        //if (isset($_GET['count']) && is_numeric($_GET['count'])) {$count = $_GET['count'];} else {$count = 6;}


        $getfield = "?query=$user+$include+$exclude";


        $twitter = new TwitterAPIExchange($settings);
        $string = json_decode($twitter->setGetfield($getfield)
        ->buildOauth($url, $requestMethod)
        ->performRequest(),$assoc = TRUE);
        if(array_key_exists("errors", $string)) {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}


        $id_array = array();


        foreach ($string['results'] as $tweets)
        {


          $id_array[] = $tweets['id_str'];


        }

      }

The code within callTwitter is the same as shown earlier.

To break my question down as simple as I can, I'll put it into parts:

Is there a common solution to updating php/api query parameters from Javascript on-the-fly?

Why doesn't the callTwitter() do anything when I call it from Javascript, and how can I get the default API call to happen before everything else on the page loads like it did before I put it within a defined function?

I'm not sure if it will help but I am using a file from Github to take care of the Oauth part of the API. This php file just has to be in the same folder as the script making the API call.

https://github.com/J7mbo/twitter-api-php/blob/master/TwitterAPIExchange.php

Updated callTwitter() function and included the js function that where I make use of the API response.

Updated callTwitter()

                function callTwitter(){
        $url = "https://api.twitter.com/1.1/tweets/search/30day/dev30.json";
        $requestMethod = "GET";
        if (isset($_GET['topic']))  {$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['topic']);}  else {$user  = "beer+-wine";}
        //if (isset($_GET['count']) && is_numeric($_GET['count'])) {$count = $_GET['count'];} else {$count = 6;}


        $getfield = "?query=(beer+wine)";


        $twitter = new TwitterAPIExchange($settings);
        $string = json_decode($twitter->setGetfield($getfield)
        ->buildOauth($url, $requestMethod)
        ->performRequest(),$assoc = TRUE);
        if(array_key_exists("errors", $string)) {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}


        $id_array = array();

        //Foreach loop to create divs

        foreach ($string['results'] as $tweets)
        {


          $id_array[] = $tweets['id_str'];

        }

        return json_encode($id_array);
      }


      $ids = callTwitter();

Beginning of Javascript that uses the Twitter API response stored in $id_array originally:

    var jsarray = <?php echo $ids ?>;

          function embedTweets()
          {
            console.log("the embed tweets function has been called.")


            jsarray.forEach(function(id, i)
            {
              twttr.widgets.createTweet(
                id, document.getElementById('mycontainer'),
                {
                  conversation : 'none',    // or all
                  cards        : 'hidden',  // or visible
                  linkColor    : '#' + background_color, // default is blue
                  theme        : 'light',    // or dark
                  align        : 'center'
                }
              ).then(function(el)
              {
                readId(el);
                console.log(el);
              });
            });

This implementation currently doesn't work. It appears callTwitter is still never being called.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 如何在scanpy上做差异基因和通路富集?
    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 截图中的mathematics程序转换成matlab
    • ¥15 动力学代码报错,维度不匹配
    • ¥15 Power query添加列问题
    • ¥50 Kubernetes&Fission&Eleasticsearch
    • ¥15 報錯:Person is not mapped,如何解決?
    • ¥15 c++头文件不能识别CDialog