2014-02-11 62 views
-1

我已经尝试了各种解决方案,但没有一个适合我的特殊情况! 我该如何做到这一点,以便当用户按下“Enter”时,表单会提交&搜索。 我也想尝试从HTML文档中移除JavaScript,并将其移至ajax.js文件&进行选择。 我不确定这样做的正确语法。 我正在用AJAX使用烂番茄API。用输入键AJAX API提交JQuery表单提交

的search.php

<form name="myform" action="" method="GET"><h3>Search for a movie here:</h3><br> 
    <input type="text" id="inputbox" value="">&nbsp; 
    <input type="button" id="button" value="Go!" onClick="filmlist(this.form)"> 
     </form> 

ajax.js

function filmlist (form) { 
$('#films table').empty(); //removes previous search results before adding the new ones. 

var apikey = "frceg2d5djxezaedgm3qq94h"; 
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0"; 
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey; 
var query = form.inputbox.value; //uses the value from the input box as the query search 



    // sends the query 
    $.ajax({ 
    url: moviesSearchUrl + '&q=' + encodeURI(query), 
    dataType: "jsonp", 
    success: searchCallback 
    }); 


// receives the results 

function searchCallback(data) { 
$('#films table').append('Found ' + data.total + ' results for ' + query); 
var movies = data.movies; 
$.each(movies, function(index, movie) { 
    $('#films table').append('<tr><td width="70" rowspan="2"><a href="' + movie.links.alternate + 
    '" title="Click here to view film information for ' + movie.title + '."><img class="ajaximage" src="' 
    + movie.posters.thumbnail + '" /></a></td><td class="ajaxfilmlisttitle"><h3><a href="' + movie.links.alternate + 
    '" title="Click here to view film information for ' + movie.title + '.">' + movie.title + '</a></h3>Release year: ' 
    + movie.year + '</td></tr><tr><td class="ajaxfilmlistinfo">Audience Score: ' + movie.ratings.audience_score + 
    '%<br>' + 'Cinema Release Date: ' + movie.release_dates.theater + 
    '<br>Runtime: ' + movie.runtime + ' minutes</td></tr>'); 
}); 
} 
} 
+0

你是什么意思“从HTML文档中删除JavaScript,并将其移动到ajax.js文档并选择它”? – Rocky

回答

0
$("form").submit(function(){ 
    $.ajax({ 
     url: moviesSearchUrl + '&q=' + encodeURI(query), 
     dataType: "jsonp", 
     success: searchCallback 
    }); 
    return false; 
}); 

,或者就在return false你filmlist函数的末尾。

-1

您可以检测与下面的jQuery代码#inputbox元素的输入按键:

$('#inputbox').keyup(function(e) 
{ 
    if(e.keyCode == 13) 
    { 
     //do your stuff 
    } 
}); 

您还可以使用$('#inputbox').change()直接加载电影,当用户输入。

不要忘记,一些旧的或移动浏览器不支持JavaScript。总是建立一个服务器端解决方案作为后备。