完成我的第一个AJAX呼叫-卡住了为什么我的结果根本不显示的原因 [英] Working through my first AJAX call - Stuck as to why my results aren't displaying at all
问题描述
在此处进行测试- http://paulmatheson.net/webdev/wiki/wikipedia -viewer.html
基本上,您输入一个词,结果应该显示在下面.我让它工作了一秒钟,但是在最后一个小时左右改变了某些东西,不知道我在哪里搞砸了.我已经分析了它,但是在代码中找不到问题.拥有更好视力/更多经验的人可以帮助我吗?
Basically, you enter a term and the results are supposed to display below. I had it working for a second but changed something in the last hour or so and don't know where I screwed up. I've analyzed it and can't find the issue in the code. Can someone with a better eye/more experience help me out?
$(document).ready(function() {
$('#random-btn').click(function() {
window.open('https://en.wikipedia.org/wiki/Special:Random');
});
$('#submit-search-btn').click(function() {
var searchTerm = $('#search-input').val();
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchTerm + "&format=json&callback=?";
$.ajax({
type: "GET",
url: url,
async: false,
dataType: "json",
success: function(data) {
var html;
$('#header').html('<h5>Wiki Search</h5');
$('.content').css('margin-top', '0');
$('#div-random-btn').remove();
for (var i = 0; i < data[1].length; i++) {
html += "<div class='listing'><h4>" + data[1][i] + "</h4><h5>" + data[2][i] + "</h5></div>";
};
$("#output-div").html(html);
},
error: function(errorMessage) {}
})
})
});
那是通话的要旨.请让我知道是否需要更彻底的分解.
That is the gist of the call. Please let me know if anything needs a more thorough break down.
推荐答案
这是因为您的button
是表单元素&其类型为submit
.所以从根本上说,表单是通过表单提交的.由于此&,您的ajax通话被取消了页面正在重新加载.您可以做两件事
It is because your button
is form element & its type is submit
. So basically what's wrong is the form is submitted via form. Your ajax call is being cancelled due to this & page is reloading. You can do two things
-
您需要通过在按钮单击时使用 preventDefault 方法来停止此事件像这样
You need to stop this event by using preventDefault method on button click like this
$('#submit-search-btn').click(function(e) {
e.preventDefault()
var searchTerm = $('#search-input').val();
//Further code
$('#submit-search-btn').click(function(e) {
e.preventDefault()
var searchTerm = $('#search-input').val();
//Further code
将button属性更改为type="button"
,这将阻止它首先提交
Change the button attribute to type="button"
which will stop it from submitting in the first place
这篇关于完成我的第一个AJAX呼叫-卡住了为什么我的结果根本不显示的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!