简体   繁体   English

跟踪页面上的 Ajax 请求

[英]Track Ajax requests on a page

I have a web page and I am associating a note with the page storing it in my database, so that the whenever the next time the page is loaded that notice can been seen till it is deleted by some other user authorized to do the same.我有一个网页,并且我将一个便笺与将其存储在我的数据库中的页面相关联,以便下次加载该页面时可以看到该通知,直到它被授权执行相同操作的其他用户删除为止。 However, say I associate a note with the page after some content is loaded through AJAX.但是,假设我在通过 AJAX 加载某些内容后将注释与页面相关联。 I want the note to appear only after that particular content has loaded next time on the web page.我希望该注释仅在该特定内容下次在网页上加载后出现。 I would like to track the AJAX request and attach the note to it?我想跟踪 AJAX 请求并附上注释? I want to do it all through simple JavaScript code put at the bottom of any web page.我想通过放在任何网页底部的简单 JavaScript 代码来完成这一切。 How can it be done?怎么做到呢?

jQuery ajax provides methods to fire events before, during and after the ajax request. jQuery ajax 提供了在 ajax 请求之前、期间和之后触发事件的方法。 Please check the api here for complete list.请在此处查看 api 以获取完整列表。

Here are couple of methods that are called after completion of every ajax request.以下是在完成每个 ajax 请求后调用的几个方法。

jQuery.ajaxComplete() - Register a handler to be called when Ajax requests complete. jQuery.ajaxComplete() - 注册一个在 Ajax 请求完成时调用的处理程序。

jQuery.ajaxSuccess() - Show a message when an Ajax request completes successfully jQuery.ajaxSuccess() - 当 Ajax 请求成功完成时显示一条消息

These functions allows you to pass a callback function to trigger after event occurs.这些函数允许您在事件发生后传递一个回调函数来触发。 In that call back function check if content you want is loaded or not, then show the note.在该回调函数中检查您想要的内容是否已加载,然后显示注释。

Sample code for the above methods can be found here:上述方法的示例代码可以在这里找到:

http://api.jquery.com/ajaxComplete/ http://api.jquery.com/ajaxComplete/

http://api.jquery.com/category/ajax/ http://api.jquery.com/category/ajax/

Hope this helps.希望这可以帮助。

You'd need to write a wrapper for all of your ajax calls that checks the result and sees if it should add a note.您需要为所有 ajax 调用编写一个包装器来检查结果并查看它是否应该添加注释。 Here's an example, assuming you're using jQuery to handle the ajax requests:这是一个示例,假设您使用 jQuery 来处理 ajax 请求:

function ajaxWrapper(settings){

    var old_callback = settings.complete;

    settings.complete = function(request, status){
        if(status == "200"){
            // check the request.responseText and add your note if appropriate 
        }

        if(old_callback){
            old_callback(request, status);
        }
    }

    jQuery.ajax(settings);
}

And then instead of calling jQuery.ajax() directly, call ajaxWrapper() instead.然后不是直接调用 jQuery.ajax(),而是调用 ajaxWrapper()。

An alternate option would be to include the note in your ajax response.另一种选择是将注释包含在您的 ajax 响应中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM