?? ajax.js
字號:
/*
General AJAX technique samples--how to talk to the server + return data and do stuff with it.
Direct questions, answers, rants, flames, kudos to sbenfield@clearnova.com
Steve Benfield
1.0: 2005-07-14 Initial Release
1.1: 2005-07-15 Fixed bugs, changed text for clarity, added ability to register for updates
*/
var _ms_XMLHttpRequest_ActiveX = ""; // Holds type of ActiveX to instantiate
var _ajax; // Reference to a global XMLHTTPRequest object for some of the samples
var _logger = true; // write output to the Activity Log
var _status_area; // will point to the area to write status messages to
if (!window.Node || !window.Node.ELEMENT_NODE) {
var Node = { ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3, CDATA_SECTION_NODE: 4, ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6, PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12 };
}
// initialize the global AJAX object
// lots of samples that discuss AJAX use a global variable
// so I started these samples with one
// some examples use the "global" one and others use an encapsulated one that requires a new (a better approach!)
_ajax = startAJAX();
// From prototype.js @ www.conio.net | Returns an object reference to one or more strings
// ignore the fact that there are no arguments to this method -- javascript doesn't care how many you send (not strongly typed)
// The method checks the actual # of arguments -- returns a single object or an array
function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
if (arguments.length == 1)
return element;
elements.push(element);
}
return elements;
}
function getTextFromXML( oNode, deep ) {
var s = "";
var nodes = oNode.childNodes;
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.nodeType == Node.TEXT_NODE) {
s += node.data;
} else if (deep == true && (node.nodeType == Node.ELEMENT_NODE || node.nodeType == Node.DOCUMENT_NODE
|| node.nodeType == Node.DOCUMENT_FRAGMENT_NODE)) {
s += getTextFromXML(node, true);
};
}
;
return s;
}
;
// If you plan on doing anything outside of the US of A, then you'd better encode the things you pass back and forth
// the escape() method in Javascript is deprecated -- should use encodeURIComponent
function encode( uri ) {
if (encodeURIComponent) {
return encodeURIComponent(uri);
}
if (escape) {
return escape(uri);
}
}
function decode( uri ) {
uri = uri.replace(/\+/g, ' ');
if (decodeURIComponent) {
return decodeURIComponent(uri);
}
if (unescape) {
return unescape(uri);
}
return uri;
}
function logger( text, clear ) {
if (_logger) {
if (!_status_area) {
_status_area = document.getElementById("status_area");
}
if (_status_area) {
if (clear) {
_status_area.value = "";
}
var old = _status_area.value;
_status_area.value = text + ((old) ? "\r\n" : "") + old;
}
}
}
function initAJAX( method, url, changeHandler, async ) {
if (typeof async == "undefined")
async = true;
if (changeHandler) {
_ajax.onreadystatechange = changeHandler;
}
if (!method) {
method = "POST";
}
method = method.toUpperCase();
method = (method.charAt(0) == "G") ? "GET" : "POST";
logger("----------------------------------------------------------------------");
logger(((async) ? "Async" : "Sync") + " " + method + ": URL: " + url);
_ajax.open(method, url, async);
if (method == "POST") {
_ajax.setRequestHeader("Connection", "close"); //overcome a bug in recent Firefox builds
_ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
_ajax.setRequestHeader("Method", "POST " + url + "HTTP/1.1");
}
}
function startAJAX() {
var _myAjax = null;
if (window.XMLHttpRequest) {
_myAjax = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// Instantiate the latest MS ActiveX Objects
var versions = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
"Microsoft.XMLHTTP"];
if (_ms_XMLHttpRequest_ActiveX) {
_myAjax = new ActiveXObject(_ms_XMLHttpRequest_ActiveX);
} else {
for (var i = 0; i < versions.length ; i++) {
try {
_myAjax = new ActiveXObject(versions[i]);
if (_myAjax) {
_ms_XMLHttpRequest_ActiveX = versions[i];
break;
}
}
catch (objException) {
// trap; try next one
}
;
}
;
}
}
return _myAjax;
}
// handle some key press events
function handleKeyUp( e ) {
e = (!e) ? window.event : e;
target = (!e.target) ? e.srcElement : e.target;
logger('keyup');
if (e.type == "keyup") {
// skip shift, alt, control keys
if (e.keyCode == 16 || e.keyCode == 17 || e.keyCode == 18) {
// do nothing
}
else {
if (target.name == "state1" && !$('state1').value) {
clearCustomersByState();
} else if (target.name == "state2" && !$('state2').value) {
clearCustomersByStateXML();
} else if (target.name == "google_search") {
if (target.value) {
getSuggest(target);
} else {
$('google_suggest_target').innerHTML = "";
}
}
}
}
}
<!------------------------------- BEGIN PING ---------------------------------------------------->
function ping() {
var url = '/custom/servlet/ReaderListener';
initAJAX("post", url, function () {
if ( _ajax.readyState == 4 ) {
logger("Response from the server: " + _ajax.responseText);
//$("ping_status").innerHTML = _ajax.responseText;
$('content:ping_status').value = _ajax.responseText;
}
});
logger("Sent To The Server: value=" + encode('teste'));
_ajax.send("value=" + encode('54545'));
}
function pingjsf() {
var url = '/admin/jsp/body/sealMonitor.jsf';
initAJAX("post", url, function () {
if ( _ajax.readyState == 4 ) {
logger("Response from the server: " + _ajax.responseText);
//$("ping_status").innerHTML = _ajax.responseText;
$('content-panel').innerHTML = _ajax.responseText;
}
});
logger("Sent To The Server: value=" + encode('teste'));
_ajax.send("value=" + encode('54545'));
pingjsfAgain();
}
function buildReport(req) {
var select = document.getElementById("ping_status");
var items = req.responseXML.getElementsByTagName("report");
// loop through <item> elements, and add each nested
// <title> element to Topics select element
for (var i = 0; i < items.length; i++) {
appendToSelect(select, i,
document.createTextNode(getElementTextNS("", "epc", items[i], 0)));
}
// clear detail display
//document.getElementById("ping_status").innerHTML = "";
}
// retrieve text of an XML document element, including
// elements using namespaces
function getElementTextNS(prefix, local, parentElem, index) {
var result = "";
if (prefix && isIE) {
// IE/Windows way of handling namespaces
result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
} else {
// the namespace versions of this method
// (getElementsByTagNameNS()) operate
// differently in Safari and Mozilla, but both
// return value with just local name, provided
// there aren't conflicts with non-namespace element
// names
result = parentElem.getElementsByTagName(local)[index];
}
if (result) {
// get text, accounting for possible
// whitespace (carriage return) text nodes
if (result.childNodes.length > 1) {
return result.childNodes[1].nodeValue;
} else {
return result.firstChild.nodeValue;
}
} else {
return "n/a";
}
}
function spam( num ) {
$('spam_time').innerHTML = "Initiating " + num + " XMLHttpRequests.";
var startTime = new Date();
startAJAX();
//_logger = false;
for (var i = 1; i <= num; i++) {
initAJAX("post", '/ThinkCAP/servlet/ping', null, false);
_ajax.send("hide=1&num=" + i);
}
var endTime = new Date()
var millis = endTime - startTime;
_logger = true;
logger("time to spam the server with " + num + " requests: " + (millis / 1000).toFixed(2) + " seconds. " + (millis / 1000 / num).toFixed(2) + " seconds per request.");
$('spam_time').innerHTML = num + " requests took " + (millis / 1000).toFixed(2) + " seconds. " + (millis / 1000 / num).toFixed(2) + " seconds per request.";
}
function getBigFile() {
// This is a fully encapsulated XMLHTTP Request
// The return function is included inside this
// Also we add a pointer back to this function's instance of _myAjax so that it can be aborted
var self = this;
// we don't use "this" throughout the function because it won't work in the anonymous function declaration
self._myAjax = startAJAX();
self._myCount = 0;
self._big_file_status = $('big_file_status');
self._big_file_status.value = 'Retrieving Large File...';
$('big_file_status_button').style.display = 'inline';
$('big_file_status_button').ajaxHandle = self._myAjax;
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -