我试图用AJAX制作搜索功能。我的意思是,我点击输入框右侧的按钮,然后显示结果而不重新加载页面。在此处查看我的 HTML ,以在当前主页中显示输入表单(前端)。
<li>
<p><input type="text" size="18" name="query"><br>
<span id=result>?</span>
<p><a href="/search" id=search>Go!</a>
</li>
然后我创建了一个 javascript 文件来执行该AJAX请求。参见:
$(function() {
var submit_form = function(e) {
$.getJSON('/search', {
query: $('input[name="query"]').val()
}, function(data) {
$('#result').text(data.result);
$('input[name=query]').focus().select();
});
return false;
};
$('a#search').bind('click', submit_form);
我的&#34; /搜索&#34;路由定义如下:
@home_blueprint.route('/search')
def search():
sql = 'SELECT "publicName", "completeName" FROM "politics" WHERE '
politicDict = request.args.get('query', 'No results were found', type=text)
print politicDict # It returns 'No results were found'
return render_template('home.html')
所以,让我们假设我写了&#34; diogo&#34;在那个输入形式中(所以它的val()应该是&#34; diogo&#34;)。因此,网址请求应该是这样的:
http://localhost:5000/search?query=diogo
这就是我得到的:
http://localhost:5000/search,因此我将politicDict( python 文件)设为&#39;无&#39;而不是&#39; diogo&#39;
任何帮助都会非常感激,
最好的问候。
编辑:修复了Python格式问题。
答案 0 :(得分:1)
这可能很晚了,但是可以帮助陷入类似问题的其他人!您的一些错误是:
preventDefault()
来阻止默认行为。在这里,我提出我的解决方案:
HTML和Javascript代码
<html>
<li>
<p><input type="text" size="18" name="query"></p>
<br>
<span id=result>?</span>
<p><a href="/search" id=search>Go!</a></p>
</li>
<div id="result">
Results will appear here!
</div>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" crossorigin="anonymous"></script>
<script>
$(document).on("click", "#search", function (e) {
e.preventDefault();
var search_term = $('input[name=query]').val().toLowerCase();
console.log(search_term )
$.ajax(
{
type: "GET",
url: "{{url_for('search')}}",
data: { "query": search_term },
success: function (response) {
$("#result").empty(); //remove whatever is there and append whatever is returned
$("#result").append(response.result) //append whatever you want to append
}
}
)
});
</script>
烧瓶代码
@home_blueprint.route('/home')
def home():
return render_template('home.html')
@home_blueprint.route('/search')
def search():
sql = 'SELECT "publicName", "completeName" FROM "politics" WHERE '
politicDict = request.args.get('query') # get the data
print politicDict # It returns 'No results were found'
return {"result":politicDict} #you can return whatever result you get from SQL here but I am just
# returning the data you sent.