如何改进/缩短这两个类似的 ajax 请求
How can I improve/shorten these 2 similar ajax requests?
我的问题很简单。这是我的代码,我发现它们是两个相似的,我如何改进/缩短这段代码?
我发现它们在很多方面都很相似,这就是我在这里问的原因。
这是我的代码,任何帮助不胜感激。
$(".follow-link").click(function(event) {
event.preventDefault();
var therel = $(this).attr('rel');
var followID = $(this).attr('rel').replace(/[^0-9]/g, '');
var thisfollow = $(this);
$.ajax({
url: '/ajax/follow.php',
type: 'POST',
data: {followwho : followID},
dataType: 'json',
success: function(data){
if (data.status) {
$('a[rel="' + therel + '"]').hide();
$('a[rel="' + therel + '"]').parent().children('.unfollow-link').fadeIn();
}
}
});
});
$(".unfollow-link").click(function(event) {
event.preventDefault();
var therel = $(this).attr('rel');
var followID = $(this).attr('rel').replace(/[^0-9]/g, '');
var thisfollow = $(this);
$.ajax({
url: '/ajax/unfollow.php',
type: 'POST',
data: {followwho : followID},
dataType: 'json',
success: function(data){
if (data.status) {
$('a[rel="' + therel + '"]').hide();
$('a[rel="' + therel + '"]').parent().children('.follow-link').fadeIn();
}
}
});
});
创建一个通用函数,并在该函数中做一些简化的清理工作:
function followAjax(event, sel, phpurl) {
event.preventDefault();
var thisfollow = $(this);
var therel = thisfollow.attr('rel');
var followID = therel.replace(/[^0-9]/g, '');
$.ajax({
url: phpurl,
type: 'POST',
data: {followwho : followID},
dataType: 'json',
success: function(data){
if (data.status) {
$('a[rel="' + therel + '"]').hide().parent().children(sel).fadeIn();
}
}
});
}
$(".unfollow-link").click(function(event) {
followAjax.call(this, event, ".follow-link", '/ajax/unfollow.php')
});
$(".follow-link").click(function(event) {
followAjax.call(this, event, ".unfollow-link", '/ajax/follow.php')
});
您可以在
两个处理程序中使用相同的函数,查找this.className
(或使用jQuery:$(this).hasClass
)然后执行适当的操作。或者你使用两个函数,在闭包中生成它们:
$(".follow-link").click(makeHandler("follow"));
$(".unfollow-link").click(makeHandler("unfollow"));
function makeHandler(action) {
return function(event) {
event.preventDefault();
var therel = $(this).attr('rel');
var followID = $(this).attr('rel').replace(/[^0-9]/g, '');
var thisfollow = $(this);
$.ajax({
url: '/ajax/'+action+'.php',
type: 'POST',
data: {followwho : followID},
dataType: 'json',
success: function(data){
// no need to ask for data.status
$('a[rel="' + therel + '"]').hide();
$('a[rel="' + therel + '"]').parent().children(action=="follow"
? '.unfollow-link'
: '.follow-link'
).fadeIn();
}
});
};
}
相关文章:
- davis.js在页面加载/重新加载上生成两个请求
- Node.js&两个请求之间的Express/Can上下文切换可以是同步代码
- 两个Post请求,并且不更改变量
- Ajax向Wicket服务器发送两个请求时出错
- 从Node.JS中的两个网站请求RSS提要
- 在两个页面上发送 AJAX 请求
- Dojo 两个 XHR 请求和回调函数仅在两者完成时触发
- 两个 JSON 请求的列表
- 这是如何处理基于从 url 获取值的两个 ajax 请求吗?
- 如何在一个按钮单击上发出两个依赖的 AJAX 请求
- 使用 jquery ajax 请求和日期格式错误解析两个参数
- 如何使用 Restangular 检查两个同时请求的完成情况
- 如何改进/缩短这两个类似的 ajax 请求
- 节点JS,从两个链接同步发出HTTPS请求
- AJAX - 同时运行两个请求,但其中一个以一定的间隔重复运行
- jQuery:如何将两个请求结果连接到json服务器
- JQuery文件上传:在data.submit()上发送两个请求
- Nodejs一次触发两个请求
- 这两个请求之间的区别
- jQuery AJAX发送两个请求