如何在单击事件上调用 jQuery AJAX?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3610525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:44:35  来源:igfitidea点击:

How to call jQuery AJAX on click event?

jqueryjquery-ui

提问by zod

I made a jQuery model.

我做了一个 jQuery 模型。

Am trying to populate data using AJAX inside that model.

我正在尝试在该模型中使用 AJAX 填充数据。

I am getting an id and using that I want to populate data using AJAX.

我得到一个 id 并使用它我想使用 AJAX 填充数据。

How should I call AJAX on click event?

我应该如何在点击事件上调用 AJAX?

Is there any other event when the model is opened or loaded?

打开或加载模型时是否还有其他事件?

The model is just the showing and hiding of div.

模型只是div的显示和隐藏。

回答by Garis M Suero

Simply using:

简单地使用:

JS:

JS:

$(document).ready(function(){
  $('a.pop').click(function() { 
    var popID = $(this).attr('rel');
    $.get('content.php', { ref:popID }, function(data) {
       $(popID+'Container').html(data);
       $(popID).dialog();
       alert('Load was performed.');
    });
    return false; // prevent default
  });
});

HTML:

HTML:

<div id="example" class="flora" title="This is my title">
    I'm in a dialog!
    <div id="exampleContainer"></div>
</div>
<a href="#" id="clickingEvent" class="pop" rel="example">click to launch</a>

It is not tested, but as I see it, it should work...

它没有经过测试,但在我看来,它应该可以工作......

回答by Nick Craver

You almost have it, you need to prevent the default action which is to follow the hrefin the link, so add either event.preventDefault()or return false, like this:

您几乎拥有它,您需要阻止跟随href链接中的默认操作,因此添加event.preventDefault()return false,如下所示:

$('a.pop').click(function(e) {                     //add e param
  var popID = $(this).attr('rel'),
      popURL = $(this).attr('href');
  $.get("content.php", { ref:id}, function(data) { //did you mean popID here?
    alert("Data Loaded: "+data ); 
  });
  e.preventDefault(); //or return false;           //prevent default action
});