简体   繁体   中英

JavaScript stop working after AJAX call

My javascript is getting locked after ajax call.

When the user press enter then i call my c# method to search the city that the user typed, and then show the temperature, but when the search ends, the javascript stops working. And i found out that the error is on these lines: var div = document.getElementById('rb-grid'); div.innerHTML = resp.responseText + div.innerHTML;

code:

$(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>

Try the following and see if it works for you:

 $(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();
                 }
             });
         }
     }
 });

Add the following as a data attribute somewhere in your html, probably on your grid:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM