目前我的AJAX调用是这样设置的,这样当检测到逗号键时,AJAX调用就会触发:
$("#selector").on("keyup", function(e) {
if (e.which === 188) {
var search = $(this).val();
function searchTag() {
return $.ajax({
cache: false,
url: url,
dataType: "json",
type: "post",
data: {search: search}
});
}
searchTag().done(function(data) {
//Success
});
}
});
我希望稍后在我的代码中重用AJAX调用作为另一个事件监听器的一部分:
$("body").on("click", ".tag", function () {
searchTag();
});
如果不重写整个调用,如何使函数独立以便可以在两种情况下使用?
答案 0 :(得分:6)
将功能移到外面:
function searchTag(data) {
var url = "yoururl";
return $.ajax({
cache: false,
url: url,
dataType: "json",
type: "post",
data: data
});
}
$("#selector").on("keyup", function(e) {
if (e.which === 188) {
var search = {search: $(this).val()};
searchTag(search).done(function(data) {
//Success
});
}
});
$("body").on("click", ".tag", function () {
searchTag({});
});
答案 1 :(得分:0)
从事件中删除该函数,并将搜索值和url作为输入添加为输入:
function searchTag(searchVal, url) {
return $.ajax({
cache: false,
url: url,
dataType: "json",
type: "post",
data: {search: searchVal}
});
}
$("body").on("click", ".tag", function () {
var searchVal = $(this).val();
var url = document.URL; //use any url here
searchTag(searchVal, url);
});
你甚至可以使用回调:
function searchTag(searchVal, url, callbck) {
return $.ajax({
cache: false,
url: url,
dataType: "json",
type: "post",
data: {search: searchVal}
}).done(function(){
callbck();
});
}
$("body").on("click", ".tag", function () {
var searchVal = $(this).val();
var url = document.URL; //use any url here
searchTag(searchVal, url, function(){
//do something here..
});
});
答案 2 :(得分:0)
这个怎么样:
///tag -> tag to search
///cb -> callback to executed on success
var searchTag = function(tag, cb) {
var url = "http://example.com";
var request = $.ajax({
cache: false,
url: url,
dataType: "json",
type: "post",
data: {search: tag}
});
request.done(cb);
}
$("#selector").on("keyup", function(e) {
if (e.which === 188) {
var search = $(this).val();
searchTag(search, function(data) {
//Success
});
}
});
$("body").on("click", ".tag", function () {
//I don't actually know where the tag to search is stored
var search = $(this).html();
searchTag(search);
});
答案 3 :(得分:0)
公开了2种方法:Reusable Ajax Post/Get发布和获取,它们都需要相同的输入参数:URL,数据以及成功和错误回调。
"use strict";
var AjaxHandler = (function($) {
var handler = {};
handler.post = function(url, data, success, error) {
$.ajax({
url: url,
type: "POST",
data: data,
success: function(result) {
success(result);
},
error: function(ex) {
error(ex);
}
});
}
handler.get = function(url, data, success, error) {
$.ajax({
url: url,
type: "GET",
data: data,
success: function(result) {
success(result);
},
error: function(ex) {
error(ex);
}
});
}
return handler;
}(jQuery));
用法示例:
AjaxHandler.post(
"http://jsonplaceholder.typicode.com/posts/1",
null,
function () { console.info('success'); },
function () { console.error('failure');}
);