У меня есть веб-страница, которая использует PHP для вызова API REST и возвращает массив JSON, который будет использован позже на странице. Этот php предназначен для запуска при загрузке (да, я понимаю, что php запускается на стороне сервера), но он выполняет запрос API по умолчанию автоматически при загрузке страницы.
У меня есть группа ввода, предназначенная для изменения параметров запроса API-запроса, который, в свою очередь, обновляет массив, которым манипулируют позже.
Я бы предположил, что обновление параметров запроса на лету является довольно распространенным делом, но единственный способ, которым я могу подумать, чтобы сделать это в моем сценарии, это вызвать мой php, чтобы сделать это с новыми параметрами.
Это вызывает 2 проблемы: 1 Если я помещаю php-код вызова API в функцию и пытаюсь вызвать его с помощью некоторого ajax, он не выполняет запрос по умолчанию при загрузке. , 2 Если вызов API отсутствует в функции, я не знаю, как вызвать его снова, когда обновил параметры из моей группы ввода.
Вызов API:
<?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
используется позже в javascript, так как установлено
var jsarray = <?php echo json_encode($id_array); ?>;
Код для моей группы ввода для получения новых параметров:
<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>
Это только для включенной части проблемы - исключение идентично, только отличается на стороне API, поэтому я не учел его.
В этот момент я хотел бы повторно запустить бит php с обновленным значением для $include
. Как упоминалось ранее - я попытался поместить весь этот php-код в функцию, например так:
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'];
}
}
Код в callTwitter такой же, как показано ранее.
Чтобы разобрать мой вопрос как можно проще, я разобью его на части:
Есть ли общее решение для обновления параметров запроса php / api из Javascript на лету?
Почему callTwitter()
ничего не делает, когда я вызываю его из Javascript, и как я могу выполнить вызов API по умолчанию до того, как все остальное на странице загрузится, как это было до того, как я поместил его в определенная функция?
Я не уверен, поможет ли это, но я использую файл из Github, чтобы позаботиться о Oauth-части API. Этот php-файл просто должен находиться в той же папке, что и скрипт, выполняющий вызов API.
https://github.com/J7mbo/twitter-api-php/blob/master/TwitterAPIExchange.php
Обновлена callTwitter()
функция и включена функция js, где я использую ответ API.
Обновлено 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();
Начало Javascript, который использует ответ API Twitter, сохраненный в $id_array
первоначально:
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);
});
});
Эта реализация в настоящее время не работает. Похоже, что callTwitter
до сих пор никогда не вызывается.