有没有人知道我是否可以更改ajax对象的responseText以便我可以对所有使用ajax请求的消息进行bootleneck并在请求来自任何地方使用responseText之前更改它们?
我看到responseText只有getter属性,因此Firefox不允许我更改它,但我希望来自我网站的所有收入消息都能通过这个新对象进行更改。
希望有人能帮助我。
感谢。
答案 0 :(得分:0)
假设您无法控制正在调用的页面......
ResponseText是故意只读的(出于各种原因)。当然,您当然可以在以下任何事件中插入中间JavaScript函数:OnSuccess,OnError和OnComplete。此功能可能会改变您的数据,并根据您的标准做出不同的响应。
<强>更新强>
正如所承诺的,下面是我用于我的一个应用程序的控制器类。请注意,USAGE区域中包含的ExceptionManager包含PeepingTom.Controller的副本。还要注意ExceptionManager被传递到控制器(作为上下文)......并且因此......它拦截所有调用。
当然,你的课程可以做一个贬低版本。如果你希望所有类都使用相同的控制器(而不是拥有自己的实例)......你当然可以这样做。
<script type="text/javascript">
var PeepingTom = (function($) {
var publicInstances = {};
// ***********************
// Controller
publicInstances.Controller = Controller;
function Controller(context, processorUrl, controllerUrl) {
// ********** PROPERTIES: **********
var Self = this;
/// <summary>Represents the context-class using this instance.</summary>
this.Context = context;
/// <summary>Represents a handle returned from a setTimeout or setInterval call which can be used to cancel the timer.</summary>
this.TimerHandle;
/// <summary>Represents a wait timer until the next long-poll is executed.</summary>
this.WaitInterval = 1000;
/// <summary>Represents a relative path to the long-poll Processor.</summary>
this.LongPollingProcessor = processorUrl;
/// <summary>Represents a relative path to the long-poll Controller.</summary>
this.LongPollingController = controllerUrl;
// ********** METHODS **********
/// <!-- Initialization -->
/// <summary>Initializes the (overall) component.</summary>
this.Initialize = function() {
if (Self.Context.GetRequestObject)
Self.SetupAjax();
else
alert("Context must implement 'GetRequestObject()'.");
}
/// <!-- Communication -->
/// <summary>Setup default values for ALL ajax requests</summary>
/// <see cref="http://api.jquery.com/jQuery.ajaxSetup/"></see>
this.SetupAjax = function() {
$.ajaxSetup({
cache: false,
type: 'POST'
});
}
/// <!-- Communication -->
/// <summary>Makes an ajax call to the long-poll Listener.</summary>
this.Fetch = function() {
$.ajax({
complete: Self.OnComplete,
data: Self.Context.GetRequestObject(),
dataType: 'json',
error: Self.OnError,
success: Self.OnSuccess,
url: Self.LongPollingProcessor
});
}
/// <summary>Logs a message to the console.</summary>
this.Log = function(message) {
if (console)
console.log(message);
}
// ********** EVENTS **********
/// <!-- Communication -->
/// <summary>A function called when the request finishes.</summary>
/// <see cref="http://api.jquery.com/jQuery.ajax/"></see>
/// <param name="xmlHttpRequest">The XMLHttpRequest object.</param>
/// <param name="status">A string containing the success or error code.</param>
this.OnComplete = function(xmlHttpRequest, status) {
if (Self.Context.OnComplete)
Self.Context.OnComplete(xmlHttpRequest, status);
}
/// <!-- Communication -->
/// <summary>Setup default values for ALL ajax requests</summary>
/// <see cref="http://api.jquery.com/jQuery.ajax/"></see>
/// <param name="xmlHttpRequest">The XMLHttpRequest itself (object).</param>
/// <param name="status">A string describing the type of error that occurred</param>
/// <param name="error">The exception object (optional).</param>
this.OnError = function(xmlHttpRequest, status, error) {
if (Self.Context.OnError)
Self.Context.OnError(xmlHttpRequest, status, error);
Self.Log("OnError - " + error);
}
/// <!-- Communication -->
/// <summary>(optional) Actions to take when the session becomes invalid.</summary>
/// <see>OnSuccess: data.SessionValid = false</see>
this.OnSessionExpired = function(data) {
if (Self.Context.OnSessionExpired)
Self.Context.OnSessionExpired(data);
if (data) {
if (data.Exception) {
Self.Log("InnerException - OnError: " + data.Exception.InnerException);
Self.Log("Message - OnError: " + data.Exception.Message);
Self.Log("Source - OnError: " + data.Exception.Source);
Self.Log("StackTrace - OnError: " + data.Exception.StackTrace);
}
}
}
/// <!-- Communication -->
/// <summary>A function to be called if the request succeeds.</summary>
/// <see cref="http://api.jquery.com/jQuery.ajax/"></see>
/// <param name="data">The data returned from the server (formatted according to the 'dataType' parameter).</param>
/// <param name="status">A string describing the status.</param>
/// <param name="xmlHttpRequest">The XMLHttpRequest object (available as of jQuery 1.4).</param>
this.OnSuccess = function(data, status, xmlHttpRequest) {
if (data == null) {
Self.OnSessionExpired(data);
}
else {
if (!data.SessionValid) {
Self.OnSessionExpired(data);
}
else {
if (Self.Context.OnSuccess)
Self.Context.OnSuccess(data, status, xmlHttpRequest);
}
}
}
}
// ***********************
// Utility
publicInstances.Utility = Utility;
function Utility() {
// ********** PROPERTIES: **********
var Self = this;
// ********** METHODS **********
/// <summary>Creates a new GUID</summary>
/// <remarks>This operational method is useful in creating unique Id's.</remarks>
this.CreateGuid = function() {
var result, i, j;
result = '';
for (j = 0; j < 32; j++) {
if (j == 8 || j == 12 || j == 16 || j == 20)
result = result + '-';
i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
result = result + i;
}
return result;
}
/// <summary>Converts a milli-second formatted-date into a normalized date format.</summary>
this.ConvertDateFromMilliSeconds = function(text) {
var match;
if (!(match = text.match(/\d+/)))
return "";
var date = new Date();
date.setTime(match[0] - 0);
return date;
}
/// <summary>Converts a date to UTC time.</summary>
this.ConvertUTCtoLocalTimeZone = function(date) {
// creates a Date in local time
var realDate = new Date(parseInt(date.substr(6)));
// converts the Date to UTC by adding or subtracting the time zone offset
var offsetMilliseconds = realDate.getTimezoneOffset() * 60 * 1000;
realDate.setTime(realDate.getTime() - offsetMilliseconds);
date = realDate.toLocaleString();
return date;
}
/// <summary>Converts a UTC date to a short-date (mm/dd/yyyy).</summary>
this.ConvertUTCtoShortDate = function(utcDate) {
var month = utcDate.getUTCMonth();
var day = utcDate.getUTCDay();
var year = utcDate.getUTCFullYear();
return month + "/" + day + "/" + year;
}
// ********** EVENTS **********
}
return publicInstances;
})(jQuery);
</script>
<强> USAGE:强>
以下是使用Controller的异常管理器的副本(上图)
<script type="text/javascript">
var ExceptionManager = (function($) {
var publicInstances = {};
// ***********************
// Observer
publicInstances.Observer = Observer;
function Observer(userControlId, asOf) {
// ********** PROPERTIES **********
var Self = this;
/// <summary>Controls long-polling communications.</summary>
this.Controller = null;
/// <summary>Represents a utility class-instance.</summary>
this.Utility = null;
/// <summary>Represents the Viewer object.</summary>
this.Viewer = null;
/// <summary>The TEMPLATE ID used in creating an observation.</summary>
this.TemplateId = "#template-exceptionManager-Exception";
/// <summary>Represents a collection of observation objects.</summary>
this.Observations = null;
/// <summary>Used to pause processing of observations.</summary>
this.Pause = false;
/// <summary>Alters the speed with which observations are processed.</summary>
this.PauseInterval = 2000;
/// <summary>Determines how long to wait until the next long-poll is executed.</summary>
this.WaitInterval = 2000;
/// <summary>The design-time Id of this user-control instance.</summary>
this.UserControlId = userControlId;
/// <summary>The datetime stamp used in determining which observations to gather-up.</summary>
this.AsOf = asOf;
/// <summary>The ID of the last observation in the current batch.</summary>
this.LastId = 0;
/// <summary>The relative path of the long-polling processor.</summary>
this.ProcessorUrl = '<%=ResolveUrl("~/Handlers/ActivityExceptionProcessor.ashx")%>';
/// <summary>The relative path of the long-polling controller.</summary>
this.ControllerUrl = '<%=ResolveUrl("~/Handlers/ActivityExceptionController.ashx")%>';
// ********** METHODS **********
/// <!-- Initialization -->
/// <summary>Initializes the Observer.</summary>
this.Initialize = function() {
// Find the activityViewer within the document (the object that manages the display-queue)
if ((activityViewer != null) && (activityViewer.IsInitialized)) {
Self.Controller = new PeepingTom.Controller(Self, Self.ProcessorUrl, Self.ControllerUrl);
Self.Controller.WaitInterval = Self.WaitInterval;
Self.Utility = new PeepingTom.Utility();
Self.Observations = new Array; // THIS objects queue of observations.
Self.Viewer = activityViewer;
Self.InitializeQueue(); // THIS objects queue of observations.
Self.Controller.Fetch();
}
else
setTimeout(Self.Initialize, 2000); // Every 2 seconds
}
/// <!-- Initialization -->
/// <summary>Initializes the queue that processes Observations.</summary>
this.InitializeQueue = function() {
if (!Self.Pause) {
if (Self.Observations.length > 0) {
var observation = Self.Observations.pop();
Self.AppendObservation(observation);
}
setTimeout(Self.InitializeQueue, Self.PauseInterval);
}
}
/// <summary>Enqueue's this observer's newly found Observations.</summary>
this.Enqueue = function(observations) {
if ($(observations).length > 0) {
var lastItem = $(observations).last();
Self.LastId = lastItem[0].Id;
$(observations).each(function() {
// Append dynamic properties
this.TemplateId = Self.TemplateId;
// Append dynamic events
this.OnProcessed = function() { Self.OnProcessed(this); };
Self.Viewer.Enqueue(this);
});
}
}
/// <summary>Returns a populated XMLHttpRequest object.</summary>
this.GetRequestObject = function() {
var request = { UserControlId: Self.UserControlId, AsOf: Self.AsOf };
return request;
}
// ********** EVENTS **********
/// <!-- Notification -->
/// <summary>Notifies this control when an observation is processed.</summary>
this.OnProcessed = function(observation) {
if (observation.Id == Self.LastId) {
Self.Controller.TimerHandle = setTimeout(function() { Self.Controller.Fetch(); }, Self.WaitInterval);
}
}
/// <!-- Communication -->
/// <summary>A function called when the request finishes.</summary>
/// <see cref="http://api.jquery.com/jQuery.ajax/"></see>
/// <param name="xmlHttpRequest">The XMLHttpRequest object.</param>
/// <param name="status">A string containing the success or error code.</param>
this.OnComplete = function(xmlHttpRequest, status) {
}
/// <!-- Communication -->
/// <summary>Setup default values for ALL ajax requests</summary>
/// <see cref="http://api.jquery.com/jQuery.ajax/"></see>
/// <param name="xmlHttpRequest">The XMLHttpRequest itself (object).</param>
/// <param name="status">A string describing the type of error that occurred</param>
/// <param name="error">The exception object (optional).</param>
this.OnError = function(xmlHttpRequest, status, error) {
Self.Controller.Log("ExceptionManager - OnError: " + error);
alert("ExceptionManager - OnError");
}
/// <!-- Communication -->
/// <summary>(optional) Actions to take when the session becomes invalid.</summary>
/// <see>OnSuccess: data.SessionValid = false</see>
this.OnSessionExpired = function(data) {
Self.Controller.Log("ExceptionManager - OnSessionExpired");
alert("ExceptionManager - OnSessionExpired");
}
/// <!-- Communication -->
/// <summary>A function to be called if the request succeeds.</summary>
/// <see cref="http://api.jquery.com/jQuery.ajax/"></see>
/// <param name="data">The data returned from the server (formatted according to the 'dataType' parameter).</param>
/// <param name="status">A string describing the status.</param>
/// <param name="xmlHttpRequest">The XMLHttpRequest object (available as of jQuery 1.4).</param>
this.OnSuccess = function(data, status, xmlHttpRequest) {
Self.AsOf = data.AsOf;
if (data.Observations) {
if (data.Observations.length > 0)
Self.Enqueue(data.Observations);
else
Self.Controller.TimerHandle = setTimeout(function() { Self.Controller.Fetch(); }, Self.WaitInterval);
}
}
}
return publicInstances;
})(jQuery);
</script>