我正在使用原型和PHP的AJAX。它对我有用,但我需要一些小改动。以下是我运行的AJAX请求代码:
JS /原型:
function ajaxRequest(url) {
new Ajax.Request( url, {
method: 'get',
onSuccess: function( transport ) {
// get json response
var json = transport.responseText.evalJSON( true );
alert(json);
},
onFailure: function() {
alert('Error with AJAX request.');
}
});
return false;
}
HTML:
<a href='javascript:ajaxRequest("/testajax/ajaxresponse");'>Testing AJAX</a>
问题:
现在我想改变我的链接:
<a href='/testajax/ajaxresponse' class='AjaxLink'>Testing AJAX</a>
因此原型函数应该捕获class='AjaxLink'
链接的点击事件,然后获得点击链接的部分href并继续。如何为这种链接更改我的上述原型函数。
由于
答案 0 :(得分:2)
如果您有Prototype 1.7,那么this way可用:
document.on('click', 'a.AjaxLink', ajaxRequest.curry('/testajax/ajaxresponse'));
否则你将不得不依赖好老Event.observe
:
$$('a.AjaxLink').invoke('observe', 'click',
ajaxRequest.curry('/testajax/ajaxresponse'));
重新阅读问题,我发现你想要使用href属性。 Jan Pfiefer非常接近。
document.on('click', 'a.AjaxLink', function(event, element) {
return ajaxRequest(element.href);
});
答案 1 :(得分:1)
这不行。你为什么想要这样的链接?如果以这种方式指定链接,则对其进行的任何单击都将跟随其href并更改实际文档的位置。阻止此类行为的唯一方法是再次添加onclick或在 $(document).ready 绑定onclick处理程序,并手动取消该事件。
<强>更新强> 但是要在与 AjaxLink 类的所有链接上绑定onclick事件,请执行请求并取消该事件:
$(document).ready(function(){
$('.AjaxLink').click(
function(e){
ajaxRequest(this.href);
event.preventDefault ? event.preventDefault() : event.returnValue = false;
}
);
});
答案 2 :(得分:1)
这将有效:
$$('a.AjaxLink').each(function(element) {
element.observe('click', function(e) {
var element = e.element()
Event.stop(e)
alert(element.href)
});
})