启动ajax会调用observer并侦听特定的url来获取url参数

时间:2017-07-22 13:15:24

标签: javascript jquery

我在另一个网站上注入了一个按钮,点击后,它触发了一个带url的ajax get请求,其中包含一些url参数。让我们这样说:

  

获取https://example.com/search/test=1&hello=world&session=123

$('#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;
      }
  }
}

1 个答案:

答案 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);
        }
    }
}