如何将我的搜索框连接到烂番茄API搜索

时间:2012-11-02 13:12:52

标签: php html rest search rotten-tomatoes

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

我在PHP部分添加了$userSearch变量。我将该变量放在urlencode函数中。我对如何继续有点迷茫。我想我需要使用AJAX jQuery,我是否需要创建一个JavaScript文件,其中包含命中API并在搜索框定义中包含“操作”的代码?我对如何解决这个问题感到有点困惑,但我很难找到一个例子。我正在构建这个 Rotten Tomatoes PHP Example

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

<!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>

1 个答案:

答案 0 :(得分:3)

在这种情况下不需要PHP。当您可以直接从JavaScript调用API时,为什么要对服务器端代码进行AJAX调用以调用API?

查看您共享链接的页面上的示例JavaScript代码:

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

相关问题