收听服务响应JavaScript [英] Listen to serve response JavaScript

查看:122
本文介绍了收听服务响应JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景



我正在为网页制作Chrome扩展程序。在这个网页中,我需要捕获当用户发出POST请求时服务器发送的响应。



目前,我们正在使用Observer模式来检查HTML页面上的更改,但这很笨拙,而且会多次触发。



Objective



我需要捕获这个响应,相应地解析它的信息,然后根据它对页面的HTML做一些动作,一些表的颜色,添加额外信息等)。

问题



我的问题在于,我不知道任何JavaScript库或纯方法允许我听服务器响应,所以我可以解析它们。



我试过的是什么



我尝试了JavaScript的 EventSource ,但是为了工作,我需要在服务器中有特定的代码,这不是一个选项。

另一个研究地点是使用 XHMLRequest 来发出请求,但我必须有一个监听器页面上的每个按钮,以便我可以停止其默认操作并通过我的代码执行它,这听起来不太好。

问题




  1. 是否有JavaScript工具允许我检查服务器反应和对待他们?


解决方案

这样的事情如何?

 (function(open){
XMLHttpRequest.prototype.open = function(m,u,a,us,p){
this.addEventListener('readystatechange',function(){
console.log(this.response);
},false);

open.call(this,m ,

})(XMLHttpRequest.prototype.open)

您可以重写打开的函数,然后使用任何您想要的响应。


Background

I am making a Chrome extension for a webpage. In this webpage, I need to catch the response that the server sends when a user makes a POST request.

Currently, we are using the Observer pattern to check changes on the HTML page, but this is clumsy and it fires several times.

Objective

I need to catch that response, parse its information accordingly, and then base on it do some actions on the page's HTML by changing (adding some colors to some tables, add additional info, etc).

Problem

My issue here, is that I don't know of any JavaScript library or pure method that allows me to listen to server responses, so I can parse them.

What I tried

I tried JavaScript's EventSource, however for it to work I need to have specific code in the server and that is not an option.

Another research venue was making the request myself using an XHMLRequest, but then I would have to have a listener on every button on the page so I could stop its default action and perform it via my code, which doesn't sound that good either.

Questions

  1. Are there any JavaScript tools that allow me to check for server responses and treat them?

解决方案

How about something like this?

(function(open) {
    XMLHttpRequest.prototype.open = function(m, u, a, us, p) {
        this.addEventListener('readystatechange', function() {
            console.log(this.response);
        }, false);

        open.call(this, m, u, a, us, p);
    };
})(XMLHttpRequest.prototype.open)

You can override open function and then do with response whatever you want.

这篇关于收听服务响应JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆