使用jquery和ajax从表单显示搜索结果

时间:2013-02-19 01:20:08

标签: jquery ajax

我有简单的表单和脚本,它接受输入数据并调用烂番茄API并显示结果。如果我不使用$('#submitid').click(function()并且var查询是硬编码结果显示正常。如果我只将$('#submitid').click(function() {})与警报结合使用,则会显示表单数据。但是在当前状态下不显示任何内容。任何帮助表示赞赏。

<form action="">
    <input  type="text" id='myid' />
    <input value="Search" type="submit" id="submitid" />
</form>

<script>
    $('#submitid').click(function () {
        var query = $('#myid').val();
        var apikey = "my_api_key_sample";
        var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";

        // construct the uri with our apikey
        var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;

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

        // callback for when we get back the results
        function searchCallback(data) {
            $(document.body).append(
                'Found ' + data.total + ' results for ' + query
            );
            var movies = data.movies;
            $.each(movies, function (index, movie) {
                var mydata += //code for appending my data 
            });

            //displaying mydata on div with id result
            $('#result').html(mydata);
        }
    })
    })
</script>

2 个答案:

答案 0 :(得分:1)

尝试:

HTML:

<form action="" id="someform">
    <input  type="text" id='myid'>
    <input value="Search" type="submit" id="submitid">
</form>

jQuery的:

$(document).ready(function() {

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

});

答案 1 :(得分:0)

var mydata += //code for appending my data

您需要完成此行或完全注释掉。此外,最后您的} }) })应为} });