我在另一个网站上注入了一个按钮,点击后,它触发了一个带url的ajax get请求,其中包含一些url参数。让我们这样说:
$('#myBtn').click(function() {
// Here
funcForTriggeringAjax()
});
有没有办法在// Here
上添加一个调用观察器来开始只观察一个特定的URL(类似https://example.com/search/*
),一旦得到结果,就会停止观察?
最后,我可以访问参数值。
完全想象的场景:
$('#myBtn').click(function() {
startAjaxObserver()
funcForTriggeringAjax()
});
startAjaxObserver() {
observingStarted(x, result) {
var url = "https://example.com/search/*";
if (x.url == url) {
console.log(result['session'])
stopObservingAjax()
}
}
}
我尝试了下面的答案,但没有运气:
$(document).ready(function() {
$('#myBtn').click(function() {
$(document).ajaxSuccess(responseHandler());
});
})
function responseHandler() {
console.log("X") // comes here
return function(event, xhr, settings) {
console.log('Y') // doesn't come here
if (settings.url == 'desired-url' && active) {
// do your thing
active = false;
}
}
}
答案 0 :(得分:0)
拦截电话
<强>的jQuery 强>
function responseHandler() {
var active = true;
return function(event, xhr, settings) {
if (settings.url == 'desired-url' && active) {
// do your thing
active = false;
}
}
}
$(document).ajaxSuccess(responseHandler());
自定义实施
function ajax(url, method, data) {
makeRequest(url, method, data, function(err, res) {
afterAjax(url, res);
});
}
function makeRequest(url, method, data, callback) {
// your implementation of executing the request
// assuming your implementation returns either error or response
if(error) {
callback(error);
} else {
callback(null, response); // send the response back
}
}
var afterAjaxStack = {};
afterAjaxStack.urlCheck = function(url, res) {
if (url === 'desired-url') {
// do your stuff
delete afterAjaxStack.urlCheck;
}
}
// put more functions on the stack if you want
afterAjax(url, res) {
for (var property in afterAjaxStack) {
if (afterAjaxStack.hasOwnProperty(property)) {
afterAjaxStack[property](url, res);
}
}
}