質問

Now that I can utilize the search function for reddit's API, I want the user to input their own query. I'm new to javascript and I think the problem with my code is that the API search function is being ran before the user even inputs the query.

HTML:

<div id="site-content">
<form name="RedditSearch">
    Enter your query:
    <input type="text" name="query" onkeydown="if (event.keyCode == 13) document.getElementById('search').click()"/>
    <input type="button" id="search" value="Search" onclick="searchquery();" />
</form>    
</div>

Javascript:

var container = $('#site-content')
function searchquery()
{
 var query = document.RedditSearch.query.value;
}
 $.getJSON("http://www.reddit.com/search.json?q=" + query, function(data) {
  $.each(data.data.children, function(i,item){
    var title = item.data.title
    var post = '<div>'+title+'</div>'
    container.append(post)        

});
});
役に立ちましたか?

解決

Indeed, it appears that your getJSON query is executed when the page loads. At that time, the user hasn't input anything yet, so it is executed too early.

You need to add an event listener which will detect user input, and then perform the AJAX call to the reddit API.

Assuming your user inputs his keywords in a text area, you could use .change().

You can fine more informations here : http://api.jquery.com/category/events/‎ or here http://www.w3schools.com/jquery/event_change.asp

Example in your case : http://jsfiddle.net/2ECG6/1/

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top