JavaScript在AJAX调用后停止工作 [英] JavaScript stop working after AJAX call
问题描述
我的javascript在ajax调用后被锁定.
My javascript is getting locked after ajax call.
当用户按下Enter键时,我调用c#方法搜索用户键入的城市,然后显示温度,但是当搜索结束时,javascript停止工作.我发现错误在于以下几行: var div = document.getElementById('rb-grid'); div.innerHTML = resp.responseText + div.innerHTML;
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;
代码:
$(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();
}
});
}
}
});
将以下内容作为数据属性添加到您的html中的某个位置(可能在网格中):
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>
这篇关于JavaScript在AJAX调用后停止工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!