2016-02-11 148 views
4

總新手,第一個項目,我沒有做得太好。需要拉一個簡單的搜索的是顯示查詢的標題YouTube視頻:如何創建通過API搜索YouTube

這裏是我的JS:

$(function() { 
 
    $('#search-term').submit(function(event) { 
 
    event.preventDefault(); 
 
    var searchTerm = $('#query').val(); 
 
    getRequest(searchTerm); 
 
    }); 
 
}); 
 

 
function getRequest(searchTerm) { 
 
    var params = { 
 
    part: 'snippet', 
 
    key: '', 
 
    q: query 
 
    }; 
 
    url = 'https://www.googleapis.com/youtube/v3/search'; 
 

 
    $.getJSON(url, params, function(data) { 
 
    showResults(data.Search); 
 
    }); 
 
} 
 

 
function showResults(results) { 
 
    var html = ""; 
 
    $.each(results, function(index, value) { 
 
    html += '<p>' + video.snippet.title + '</p>'; 
 
    console.log(video.snippet.title); 
 
    }); 
 
    $('#search-results').html(html); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <title>Youtube Project</title> 
 
</head> 
 

 
<body> 
 
    <form id="search-term"> 
 
    Entry: 
 
    <br> 
 
    <input id="query" type="text"> 
 
    <br> 
 
    <input type="submit" value="Submit"> 
 
    </form> 
 
    <div id="search-results"> 
 
    </div> 
 
</body> 
 

 
</html>

去容易對我來說,任何幫助表示讚賞,這裏jsfiddle: https://jsfiddle.net/jelane20/3hbrv12k/1/

回答

4

知道了!

$(document).ready(function() { 
 
    $('#search-term').submit(function (event) { 
 
     event.preventDefault(); 
 
     var searchTerm = $('#query').val(); 
 
     getRequest(searchTerm); 
 
    }); 
 
}); 
 

 
function getRequest(searchTerm) { 
 
    url = 'https://www.googleapis.com/youtube/v3/search'; 
 
    var params = { 
 
     part: 'snippet', 
 
     key: 'XXXXXX', 
 
     q: searchTerm 
 
    }; 
 
    
 
    $.getJSON(url, params, function (searchTerm) { 
 
     showResults(searchTerm); 
 
    }); 
 
} 
 

 
function showResults(results) { 
 
    var html = ""; 
 
    var entries = results.items; 
 
    
 
    $.each(entries, function (index, value) { 
 
     var title = value.snippet.title; 
 
     var thumbnail = value.snippet.thumbnails.default.url; 
 
     html += '<p>' + title + '</p>'; 
 
     html += '<img src="' + thumbnail + '">'; 
 
    }); 
 
    
 
    $('#search-results').html(html); 
 
}

+0

不知道你的意思@AakashVerma,我把虛擬按鍵 – Jenny

+0

哦,好吧。只是看起來像你忘了這樣做,並已經把你的原始鑰匙。 –