📄 dwr-engine.js
字号:
var batch = dwr.engine._createBatch();
batch.map.id = 0; // TODO: Do we need this??
batch.map.callCount = 1;
batch.map.partialResponse = (document.all) ? "false" : "true";
batch.isPoll = true;
batch.rpcType = dwr.engine._pollType;
batch.httpMethod = "POST";
batch.async = true;
batch.timeout = 0;
batch.path = (overridePath) ? overridePath : dwr.engine._defaultPath;
batch.preHooks = [];
batch.postHooks = [];
batch.handlers[0] = {
callback:function(pause) {
dwr.engine._cometBatch = null;
setTimeout("dwr.engine._poll()", pause);
}
};
// Send the data
dwr.engine._sendData(batch);
if (batch.map.partialResponse == "true") {
dwr.engine._cometBatch = batch;
dwr.engine._checkCometPoll();
}
};
/** @private Generate a new standard batch */
dwr.engine._createBatch = function() {
var batch = {
map:{
callCount:0,
page:window.location.pathname,
httpSessionId:dwr.engine._getJSessionId(),
scriptSessionId:dwr.engine._getScriptSessionId()
},
paramCount:0, // TODO: What's this for?
isPoll:false, headers:{}, handlers:{}, preHooks:[], postHooks:[],
rpcType:dwr.engine._rpcType,
httpMethod:dwr.engine._httpMethod,
async:dwr.engine._async,
timeout:dwr.engine._timeout,
errorHandler:dwr.engine._errorHandler,
warningHandler:dwr.engine._warningHandler,
textHtmlHandler:dwr.engine._textHtmlHandler
};
if (dwr.engine._preHook) batch.preHooks.push(dwr.engine._preHook);
if (dwr.engine._postHook) batch.postHooks.push(dwr.engine._postHook);
var propname, data;
if (dwr.engine._headers) {
for (propname in dwr.engine._headers) {
data = dwr.engine._headers[propname];
if (typeof data != "function") batch.headers[propname] = "" + data;
}
}
if (dwr.engine._parameters) {
for (propname in dwr.engine._parameters) {
data = dwr.engine._parameters[propname];
if (typeof data != "function") batch.parameters[propname] = "" + data;
}
}
return batch;
}
/** @private Take further options and merge them into */
dwr.engine._mergeBatch = function(batch, overrides) {
var propname, data;
for (var i = 0; i < dwr.engine._propnames.length; i++) {
propname = dwr.engine._propnames[i];
if (overrides[propname] != null) batch[propname] = overrides[propname];
}
if (overrides.preHook != null) batch.preHooks.unshift(overrides.preHook);
if (overrides.postHook != null) batch.postHooks.push(overrides.postHook);
if (overrides.headers) {
for (propname in overrides.headers) {
data = overrides[propname];
if (typeof data != "function") batch.headers[propname] = "" + data;
}
}
if (overrides.parameters) {
for (propname in overrides.parameters) {
data = overrides[propname];
if (typeof data != "function") batch.map[propname] = "" + data;
}
}
};
/** @private What is our session id? */
dwr.engine._getJSessionId = function() {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
while (cookie.charAt(0) == ' ') cookie = cookie.substring(1, cookie.length);
if (cookie.indexOf(dwr.engine._sessionCookieName + "=") == 0) {
return cookie.substring(11, cookie.length);
}
}
return "";
}
/** @private Check for reverse Ajax activity */
dwr.engine._checkCometPoll = function() {
if (dwr.engine._pollComet) {
// If the poll resources are still there, come back again
//if (dwr.engine._pollFrame || dwr.engine._pollReq) {
// setTimeout("dwr.engine._checkCometPoll()", dwr.engine._pollCometInterval);
//}
try {
dwr.engine._receivedBatch = dwr.engine._cometBatch;
if (dwr.engine._pollFrame) {
var text = dwr.engine._getTextFromCometIFrame();
dwr.engine._processCometResponse(text);
}
else if (dwr.engine._pollReq) {
var xhrtext = dwr.engine._pollReq.responseText;
dwr.engine._processCometResponse(xhrtext);
}
dwr.engine._receivedBatch = null;
}
catch (ex) {
// IE complains for no good reason for both options above. Ignore.
}
// If the poll resources are still there, come back again
if (dwr.engine._pollFrame || dwr.engine._pollReq) {
setTimeout("dwr.engine._checkCometPoll()", dwr.engine._pollCometInterval);
}
}
};
/** @private Extract the whole (executed an all) text from the current iframe */
dwr.engine._getTextFromCometIFrame = function() {
var frameDocument;
if (dwr.engine._pollFrame.contentDocument) {
frameDocument = dwr.engine._pollFrame.contentDocument.defaultView.document;
}
else if (dwr.engine._pollFrame.contentWindow) {
frameDocument = dwr.engine._pollFrame.contentWindow.document;
}
else {
return "";
}
var bodyNodes = frameDocument.getElementsByTagName("body");
if (bodyNodes == null || bodyNodes.length == 0) return "";
if (bodyNodes[0] == null) return "";
var text = bodyNodes[0].innerHTML.toString();
// IE plays silly-pants and adds <PRE>...</PRE> for some unknown reason
if (text.indexOf("<PRE>") == 0) text = text.substring(5, text.length - 7);
return text;
};
/** @private Some more text might have come in, test and execute the new stuff */
dwr.engine._processCometResponse = function(response) {
if (dwr.engine._cometProcessed != response.length) {
if (response.length == 0) {
dwr.engine._cometProcessed = 0;
}
else {
// dwr.engine._debug("response.length=" + response.length + ", cometProcessed=" + dwr.engine._cometProcessed + ", extra chars=" + (response.length - dwr.engine._cometProcessed));
var firstStartTag = response.indexOf("//#DWR-START#", dwr.engine._cometProcessed);
// dwr.engine._debug("firstStartTag='" + firstStartTag + "'");
if (firstStartTag == -1) {
// dwr.engine._debug("Failed to find start tag when starting at " + firstStartTag + ". Dropping: " + (response.length - dwr.engine._cometProcessed) + " characters");
dwr.engine._cometProcessed = response.length;
}
else {
var lastEndTag = response.lastIndexOf("//#DWR-END#");
// dwr.engine._debug("lastEndTag='" + lastEndTag + "'");
if (lastEndTag != -1) {
var exec = response.substring(firstStartTag + 13, lastEndTag);
// Skip the end tag too for next time, remembering CR and LF
if (response.charCodeAt(lastEndTag + 11) == 13 && response.charCodeAt(lastEndTag + 12) == 10) {
dwr.engine._cometProcessed = lastEndTag + 13;
}
else {
dwr.engine._cometProcessed = lastEndTag + 11;
}
dwr.engine._eval(exec);
// dwr.engine._debug("setting _cometProcessed='" + dwr.engine._cometProcessed + "'");
}
// else {
// dwr.engine._debug("No end tag. (yet) '" + response + "'");
// }
}
}
}
};
/** @private Actually send the block of data in the batch object. */
dwr.engine._sendData = function(batch) {
batch.map.batchId = dwr.engine._nextBatchId++;
dwr.engine._batches[batch.map.batchId] = batch;
dwr.engine._batchesLength++;
batch.completed = false;
for (var i = 0; i < batch.preHooks.length; i++) {
batch.preHooks[i]();
}
batch.preHooks = null;
// Set a timeout
if (batch.timeout && batch.timeout != 0) {
batch.interval = setInterval(function() { dwr.engine._abortRequest(batch); }, batch.timeout);
}
// Get setup for XMLHttpRequest if possible
if (batch.rpcType == dwr.engine.XMLHttpRequest) {
if (window.XMLHttpRequest) {
batch.req = new XMLHttpRequest();
}
// IE5 for the mac claims to support window.ActiveXObject, but throws an error when it's used
else if (window.ActiveXObject && !(navigator.userAgent.indexOf("Mac") >= 0 && navigator.userAgent.indexOf("MSIE") >= 0)) {
batch.req = dwr.engine._newActiveXObject(dwr.engine._XMLHTTP);
}
}
var prop, request;
if (batch.req) {
// Proceed using XMLHttpRequest
if (batch.async) {
batch.req.onreadystatechange = function() { dwr.engine._stateChange(batch); };
}
// If we're polling, record this for monitoring
if (batch.isPoll) dwr.engine._pollReq = batch.req;
// Workaround for Safari 1.x POST bug
var indexSafari = navigator.userAgent.indexOf("Safari/");
if (indexSafari >= 0) {
if (dwr.engine._allowGetForSafariButMakeForgeryEasier)
{
var version = navigator.userAgent.substring(indexSafari + 7);
if (parseInt(version, 10) < 400) batch.httpMethod = "GET";
}
else {
dwr.engine._handleWarning(batch, { name:"dwr.engine.oldSafari", message:"Safari GET support disabled. See http://getahead.ltd.uk/dwr/server/servlet and allowGetForSafariButMakeForgeryEasier." });
}
}
batch.mode = batch.isPoll ? dwr.engine._ModePlainPoll : dwr.engine._ModePlainCall;
request = dwr.engine._constructRequest(batch);
try {
batch.req.open(batch.httpMethod, request.url, batch.async);
try {
for (prop in batch.headers) {
var value = batch.headers[prop];
if (typeof value == "string") batch.req.setRequestHeader(prop, value);
}
if (!batch.headers["Content-Type"]) batch.req.setRequestHeader("Content-Type", "text/plain");
}
catch (ex) {
dwr.engine._handleWarning(batch, ex);
}
batch.req.send(request.body);
if (!batch.async) dwr.engine._stateChange(batch);
}
catch (ex) {
dwr.engine._handleError(batch, ex);
}
}
else if (batch.rpcType != dwr.engine.ScriptTag) {
var idname = "dwr-if-" + batch.map["c0-id"];
// Proceed using iframe
batch.div = document.createElement("div");
batch.div.innerHTML = "<iframe src='javascript:void(0)' frameborder='0' width='0' height='0' id='" + idname + "' name='" + idname + "'></iframe>";
document.body.appendChild(batch.div);
batch.iframe = document.getElementById(idname);
batch.iframe.setAttribute("style", "width:0px; height:0px; border:0px;");
batch.iframe.batch = batch;
batch.mode = batch.isPoll ? dwr.engine._ModeHtmlPoll : dwr.engine._ModeHtmlCall;
if (batch.isPoll) {
// Settings that vary if we are polling
dwr.engine._pollFrame = batch.iframe;
dwr.engine._cometProcessed = 0;
}
request = dwr.engine._constructRequest(batch);
if (batch.httpMethod == "GET") {
batch.iframe.setAttribute("src", request.url);
document.body.appendChild(batch.iframe);
}
else {
batch.form = document.createElement("form");
batch.form.setAttribute("id", "dwr-form");
batch.form.setAttribute("action", request.url);
batch.form.setAttribute("target", idname);
batch.form.target = idname;
batch.form.setAttribute("method", batch.httpMethod);
for (prop in batch.map) {
var value = batch.map[prop];
if (typeof value != "function") {
var formInput = document.createElement("input");
formInput.setAttribute("type", "hidden");
formInput.setAttribute("name", prop);
formInput.setAttribute("value", value);
batch.form.appendChild(formInput);
}
}
document.body.appendChild(batch.form);
batch.form.submit();
}
}
else {
batch.httpMethod = "GET"; // There's no such thing as ScriptTag using POST
batch.mode = batch.isPoll ? dwr.engine._ModePlainPoll : dwr.engine._ModePlainCall;
request = dwr.engine._constructRequest(batch);
batch.script = document.createElement("script");
batch.script.id = "dwr-st-" + batch.map["c0-id"];
batch.script.src = request.url;
document.body.appendChild(batch.script);
}
};
dwr.engine._ModePlainCall = "/call/plaincall/";
dwr.engine._ModeHtmlCall = "/call/htmlcall/";
dwr.engine._ModePlainPoll = "/call/plainpoll/";
dwr.engine._ModeHtmlPoll = "/call/htmlpoll/";
/** @private Work out what the URL should look like */
dwr.engine._constructRequest = function(batch) {
// A quick string to help people that use web log analysers
var request = { url:batch.path + batch.mode, body:null };
if (batch.isPoll == true) {
request.url += "ReverseAjax.dwr";
}
else if (batch.map.callCount == 1) {
request.url += batch.map["c0-scriptName"] + "." + batch.map["c0-methodName"] + ".dwr";
}
else {
request.url += "Multiple." + batch.map.callCount + ".dwr";
}
// Play nice with url re-writing
var sessionMatch = location.href.match(/jsessionid=(\w+)/);
if (sessionMatch != null) {
request.url += ";jsessionid=" + sessionMatch[1];
}
var prop;
if (batch.httpMethod == "GET") {
// Some browsers (Opera/Safari2) seem to fail to convert the callCount value
// to a string in the loop below so we do it manually here.
batch.map.callCount = "" + batch.map.callCount;
request.url += "?";
for (prop in batch.map) {
if (typeof batch.map[prop] != "function") {
request.url += encodeURIComponent(prop) + "=" + encodeURIComponent(batch.map[prop]) + "&";
}
}
request.url = request.url.substring(0, request.url.length - 1);
}
else {
// PERFORMANCE: for iframe mode this is thrown away.
request.body = "";
for (prop in batch.map) {
if (typeof batch.map[prop] != "function") {
request.body += prop + "=" + batch.map[prop] + dwr.engine._postSeperator;
}
}
request.body = dwr.engine._contentRewriteHandler(request.body);
}
request.url = dwr.engine._urlRewriteHandler(request.url);
return request;
};
/** @private Called by XMLHttpRequest to indicate that something has happened */
dwr.engine._stateChange = function(batch) {
var toEval;
if (batch.completed) {
dwr.engine._debug("Error: _stateChange() with batch.completed");
return;
}
try {
if (batch.req.readyState != 4) return;
}
catch (ex) {
dwr.engine._handleWarning(batch, ex);
// It's broken - clear up and forget this call
dwr.engine._clearUp(batch);
return;
}
try {
var reply = batch.req.responseText;
reply = dwr.engine._replyRewriteHandler(reply);
var status = batch.req.status; // causes Mozilla to except on page moves
if (reply == null || reply == "") {
dwr.engine._handleWarning(batch, { name:"dwr.engine.missingData", message:"No data received from server" });
}
else if (status != 200) {
dwr.engine._handleError(batch, { name:"dwr.engine.http." + status, message:batch.req.statusText });
}
else {
var contentType = batch.req.getResponseHeader("Content-Type");
if (!contentType.match(/^text\/plain/) && !contentType.match(/^text\/javascript/)) {
if (contentType.match(/^text\/html/) && typeof batch.textHtmlHandler == "function") {
batch.textHtmlHandler();
}
else {
dwr.engine._handleWarning(batch, { name:"dwr.engine.invalidMimeType", message:"Invalid content type: '" + contentType + "'" });
}
}
else {
// Comet replies might have already partially executed
if (batch.req == dwr.engine._pollReq && batch.map.partialResponse == "true") {
dwr.engine._receivedBatch = batch;
dwr.engine._processCometResponse(reply);
dwr.engine._receivedBatch = null;
}
else {
if (reply.search("//#DWR") == -1) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -