AJAX调用后JavaScript停止工作

时间:2014-03-27 17:29:51

标签: c# javascript jquery ajax

我的javascript在ajax调用后被锁定。

当用户按回车键然后我调用我的c#方法搜索用户输入的城市,然后显示温度,但是当搜索结束时,javascript停止工作。我发现错误在这些方面:                     var div = document.getElementById('rb-grid');                     div.innerHTML = resp.responseText + div.innerHTML;

代码:

$(document).ready(function () {
    $('#search-bar').keyup(function (event) {
        if (event.keyCode == 13) {

            myFunction();

        }
    });

    function myFunction() {
        var city = $('#search-bar').val();
        $.ajax({
            url: '@Url.Action("getWeatherSearch", "Index")',
            data: { city: city },
            async: false,
            complete: function (resp) {
                var div = document.getElementById('rb-grid');
                div.innerHTML = resp.responseText + div.innerHTML;
                Boxgrid.init();
            }
        });
    } });

HTML:

            <div align="center" class="div-search-bar">
                @Html.TextBox("search-bar", "", new { @class = "search-bar", placeholder = "search" })
            </div>

1 个答案:

答案 0 :(得分:0)

尝试以下操作,看看它是否适合您:

 $(function () {
     var $searchbar = $('#search-bar'),
         $grid = $('#rb-grid');

     if ($grid.length) {
         $searchbar.on('keyup', function (event) {
             if (event.keyCode == 13) {
                 myFunction();

             }
         });

         function myFunction() {
             var city = $searchbar.val();
             $.ajax({
                 url: $.grid.data('weather-url'),
                 data: { city: city }
             })
             .done(function (resp) {
                     $grid.html(resp.responseText + $grid.html());
                     Boxgrid.init();
                 }
             });
         }
     }
 });

在html中的某处添加以下数据属性,可能在你的网格上:

 <div id='rb-grid' data-weather-url='@Url.Action("getWeatherSearch", "Index")'></div>