0

如何让我的搜索框与烂番茄 API 连接,以便我可以在我的网页中进行搜索并返回烂番茄的结果?

$userSearch在 PHP 部分添加了变量。我把那个变量放在urlencode函数中。我对如何进行有点迷茫。我想我需要使用 AJAX jQuery,我是否需要创建一个 JavaScript 文件,其中包含用于访问 API 的代码并在我的搜索框定义中有一个“动作”?我对如何解决这个问题有点困惑,并且很难找到一个例子。我正在构建这个 烂番茄 PHP 示例

这是我的代码,带有硬编码的“鼠标”搜索:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>

        <form method="post" action="www.websitehere.com/folderhere/"
              name="searchform" id="searchform">

            <label for="Search"> Search: </label>
            <input type="text" id="search" name="myName" placeholder="Search for movie" 
                   required="required" style="width: 520px" />

            <label for="category" id="category">Category</label>
            <select>
                <option value="title" selected="selected">Movie Title</option>
                <option value="director">Director</option>
                <option value="genre">Genre</option>
            </select>
            <input type="submit" value="Search" id="searchbtn">
            <input type="submit" value="Add" id="searchbtn">
            <p></p>
            <div id="search_results">Local Search results</div>

        </form>

        <?php
        $userSearch = 'Mouse';
        $apikey = 'myapikeyhiddenforprivacy';
        $q = urlencode($userSearch); // make sure to url encode an query parameters
// construct the query with our apikey and the query we want to make
        $endpoint = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=' . $apikey . '&q=' . $q;

// setup curl to make a call to the endpoint
        $session = curl_init($endpoint);

// indicates that we want the response back
        curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

// exec curl and get the data back
        $data = curl_exec($session);

// remember to close the curl session once we are finished retrieveing the data
        curl_close($session);

// decode the json data to make it easier to parse the php
        $search_results = json_decode($data);
        if ($search_results === NULL)
            die('Error parsing json');

// play with the data!
        $movies = $search_results->movies;
        echo '<ul>';
        foreach ($movies as $movie) {
            echo '<li><a href="' . $movie->links->alternate . '">' . $movie->title . " (" . $movie->year . ")</a></li>";
            echo '<img src="' . $movie->posters->detailed . ' "/><br>';
        }
        echo '</ul>';
        ?>

    </body>
</html>
4

1 回答 1

3

There is no need for PHP in this scenario. Why make an AJAX call to your server side code to make a call to the API when you can call to the API directly from JavaScript?

Take a look at the example JavaScript code on the page you shared a link to:

http://developer.rottentomatoes.com/docs/read/json/v10/examples#JavaScript

于 2012-11-02T13:17:36.217 回答