我正在与原型和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部分,然后继续。我怎样才能把上面的原型函数改成这样的链接呢?
谢谢
如果你有Prototype 1.7,那么这种方式是可用的:
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);
});
这行不通。你为什么想要这样的链接?如果以这种方式指定链接,任何点击它都将跟随它的href并更改实际文档的位置。防止这种行为的唯一方法是再次添加onclick或在$(document)中。准备好绑定onclick处理程序,并手动取消事件。
然而,要用AjaxLink类在所有链接上绑定onclick事件,执行request并取消事件:
$(document).ready(function(){
$('.AjaxLink').click(
function(e){
ajaxRequest(this.href);
event.preventDefault ? event.preventDefault() : event.returnValue = false;
}
);
});
可以:
$$('a.AjaxLink').each(function(element) {
element.observe('click', function(e) {
var element = e.element()
Event.stop(e)
alert(element.href)
});
})