如何只调用一次ajax
我从这段代码调用函数:
我的function是
function showNews() { //other js which show block jQuery("#loader").show(); //ajax which load content to block jQuery.ajax({ type: "GET", url: link, dataType: "html", success: function(data) { jQuery('#top-info-news').html(data); }, complete: function(){ jQuery('#loader').hide(); }, }); }
我怎样才能进行一次ajax调用? 所以当加载内容并且页面没有被刷新而不加载ajax时? 我试图做布尔变量,但没有,我支持它是因为我每次调用函数。 请告诉我怎么做。
谢谢
当你想在那个事件上做点什么的时候。
确定何时已加载数据。
var loaded = false; function showNews() { //other js which show block jQuery("#loader").show(); if(loaded) return; //ajax which load content to block jQuery.ajax({ type: "GET", url: link, dataType: "html", success: function(data) { jQuery('#top-info-news').html(data); }, complete: function(){ jQuery('#loader').hide(); }, }); loaded = true; }
或者使用one.
当你想打电话一次。
jQuery('.showNews').one('click', function() { // your code });
"Attach a handler to an event for the elements. The handler is executed at most once per element."
参考
使用.one()
函数:
将处理程序附加到元素的事件。 每个元素最多执行一次处理程序。
我已经为锚添加了一个id
属性以允许更容易绑定,但你可以使用$("#header-button-news a").one
$(document).ready(function () { $('#shownews').one('click', function (evt) { evt.preventDefault(); // prevent default click action jQuery("#loader").show(); //ajax which load content to block jQuery.ajax({ type: "GET", url: link, dataType: "html", success: function (data) { jQuery('#top-info-news').html(data); }, complete: function () { jQuery('#loader').hide(); }, }); }); });
还使用event.preventDefault()
来防止跟踪锚上的默认操作
在JS中:
$(function(){ $('a#a_news').one('click',showNews); })