前端< script >部分
$(document).ready(function () {
$('#key').bind('keypress', function (event) {
if (event.keyCode == "13") {
event.preventDefault();
$("#btn").click();
}
}); // 这一段是绑定button和回车按钮的
$("#btn").click(function () {
// 获得关键字
var keyword = $("#key").val();
//
$.ajax({
type: 'post',
url: '/problem/search/',
// dataType: 'json',
// data: JSON.stringify({kk: keyword}),
data: {kk: keyword},
success: function (result) {
var tbl = $('#tbl');
// 删除表格除第一行以外所有数据
tbl.find('tr:gt(0)').remove();
for (var i = 0; i < result.length; i++) {
var d = result[i];
var s = '<tr>';
s += '<td>' + d['p_id'] + '</td>';
s += '<td><a href="/problem/detail/' + d['p_id'] + '">' + d['p_title'] + '</a></td>';
s += '<td>' + d['p_difficulty'] + '</td>';
s += '<td>' + d['p_submit'] + '</td>';
s += '<td>' + d['p_accept'] + '</td>';
s += '</tr>';
tbl.append($(s));
}
$("#cform")[0].reset();
console.log(result);
},
error: function () {
alert("没有搜索到题目!" +
"请检查关键词是否正确!")
}
});
});
});
后台:
@csrf_exempt
def problem_search(request):
if request.method == 'POST' or request.method == 'onkeydown':
keyword = request.POST.get('kk')
print(keyword)
if keyword:
searched_problems = ' '
searched_problems = Problem.objects.filter(p_title__contains=keyword)
res = []
for s in searched_problems:
d = dict()
d['p_id'] = s.p_id
d['p_title'] = s.p_title
d['p_difficulty'] = s.p_difficulty
d['p_submit'] = s.p_submit
d['p_accept'] = s.p_accept
# other values
res.append(d)
return HttpResponse(json.dumps(res), content_type='application/json')