只是为了添加一个避免需要发布或 AJAX 的答案,以表明这可以在没有任何一个的情况下完成。
图像标签通信
您可以使用图像标签与服务器通信:
<div class="image">
<img src="image/to/be/favourited.jpg" data-aid="123" />
<a href="favoriet-fallback.php?aid=123">
<img src="/media/img/icons/twitter.png" />
</a>
</div>
<script>
jQuery(function(){
jQuery('.image > a').click(function(){
var
img = $(this).siblings('img'),
src = img.attr('src'),
aid = img.attr('data-aid'),
esc = window.encodeURIComponent ? encodeURIComponent : escape
;
/// here you have the choice of using the image to be favourited or
/// the twitter icon. I chose the favourited image for this example.
img.attr('src', 'favoriet.php?src=' + esc(src) + '&aid=' + esc(aid) );
return false;
});
});
</script>
使用此代码,您需要进行修改favoriet.php
,以便它可以src
使用简单的readfile
方法返回指定的图像,并且创建一个favoriet-fallback.php
虽然不是 100% 必要的,但它会很好。
脚本/图像标签注入
您还可以注入新的脚本或图像标签来执行您的请求。
<script>
jQuery(function(){
jQuery('.image > a').click(function(){
var
img = $(this).siblings('img'),
src = img.attr('src'),
aid = img.attr('data-aid'),
esc = window.encodeURIComponent ? encodeURIComponent : escape
;
/// you could build a script tag or a pixel image here
var script = document.createElement('script');
script.src = 'favoriet.php?src=' + esc(src) + '&aid=' + esc(aid);
jQuery('body').append(script);
return false;
});
});
</script>
这个例子显然意味着favoriet.php
应该返回可以与现有页面交互的成熟的 JavaScript。
以上只是一些使用 GET 请求代替 POST 的愚蠢示例——这确实有它的好处,也有它自己的缺点。这些示例都不需要 jQuery,我只是为了速度和清晰度而使用它。
Hugo 的设计要优雅得多,但我只提到这些只是为了证明 AJAX 不是唯一的方法。