De:Xajax 0.5: Tipps und Tricks: Neue Funktionen






De:Xajax 0.5: Tipps und Tricks: Neue Funktionen

Deutsche Übersetzung | Startseite
xajax Version: 0.5 | Original
Diese Übersetzung wurde als fehlerhaft markiert. Sie ist vermutlich veraltet, könnte aber auch inhaltliche Fehler enthalten. Bitte aktualisiere diesen Artikel anhand der Originalversion und entferne diesen Baustein.

Contents

[edit] Synchrone Requests

Seit xajax 0.5 beta 2 ist es möglich synchrone Requests zu starten. Das bedeutet, dass man eine xajax-fähige Funktion aufrufen kann und der Browser dann auf die Antwort der Anfrage wartet, bevor der restliche Javascriptcode ausgeführt wird.

Außerdem kann man einen Wert von der PHP-Funktion zurückgeben lassen um ihn im Javascript nach dem xajax Funktionsaufruf zu verwenden

[edit] Benutzung

(Javascript)
xajax.call('myFunction', {mode:'synchronous'});

(PHP)
function myFunction() {
    $objResponse = new xajaxResponse();
    $objResponse->assign('divID', 'innerHTML', 'some new content');
    return $objResponse;
}

Um einen Wert von der xajax-fähigen Funktion zurückzugeben, benutze:

(Javascript)
var myValue = xajax.call('myFunction', {mode:'synchronous'});
alert(myValue);

(PHP)
function myFunction() {
    $objResponse = new xajaxResponse();
    $objResponse->setReturnValue('Hello World!');
    return $objResponse;
}

[edit] Vorteile

(coming soon)

[edit] Nachteile

Einige xajax Antwort-Befehle gehen in einen Warte-Modus um auf den Abschluss einer Aktion zu warten. Dies kann zu Problemen mit der Abarbeitung einer synchronen Anfrage führen, bei der die synchrone Anfrage scheinbar abgeschlossen ist. Der angegebene Rückgabewert wird übergeben sobald der Warte-Modus beginnt. Dieses Verhalten unterscheidet sich vom normalen Ablauf, bei dem der synchrone Request erst beendet wird wenn alle xajax-Antwortbefehle abgearbeitet wurden. Zurzeit erzeugt nur der waitForCSS Antwortbefehl dieses Verhalten. Aus diesem Grund wird empfohlen die Benutzung von waitForCSS zusammen mit synchronen Requests zu vermeiden.

Aufgrund der Natur von synchronen Anfragen wird der Browser während einer solchen Anfrage die Ausführung von Javascript komplett unterbrechen bis die Anfrage beantwortet wurde oder der Request eine Zeitüberschreitung verursacht. Daher ist es xajax nicht möglich eine Anfrage vorher abzubrechen. (siehe Anfrage bei Zeitüberschreitung abbrechen weiter unten)


[edit] Server Redirect

Seit xajax 0.5 beta 2 behandelt der xajax-Antwortverarbeiter einen serverseitigen Redirect automatisch. Dies ist hilfreich wenn man beispielsweise auf eine geschütze Seite zugreift und der Login des Benutzers ausläuft. Der Server sollte dann einen Browser Redirect (Code 3XX) übermitteln. Wenn man will, kann man weiterhin die xajax Antwort verwenden:

$objResponse->redirect('http://myURL');

... oder man fängt an das zu benutzen:

header('location: http://myURL');


[edit] Eigene Antwortverarbeitung

Eigene Antwortverarbeitung wurde in xajax 0.5 beta 1 hinzugefüggt, damit kann man eine Funktion festlegen die aufgerufen wird, sobald die Antwort vom Server erhalten wurde. Die Funktion wird auch im Falle eines Serverfehler oder Redirects aufgerufen, unabhängig vom Inhalt der Antwort. So hat die Funktion die volle Kontrolle.

Beachtet, es muss dafür gesorgt werden dass xajax in den Normalzustand zurückversetzt wird, dafrü sollte xajax.completeResponse aufgerufen werden wie im folgenden Codebeispiel. Ansonsten werden der Wartecursor und Statuszeilentexte, neben anderen Dingen, fehlerhaft sein.

Um dieses Feature zu nutzen muss eine PHP-Funktion gegeben sein die eine entsprechende Antwort liefert.

function testXmlResponse()
{
	// XML-Daten direkt zurückgeben
	header('Content-type: text/xml; charset="utf-8"');
	return '<?xml version="1.0" encoding="utf-8" ?'.'><root><data>text</data></root>';
}

function testTextResponse()
{
	// Text-Daten direkt zurückgeben
	return 'text data';
}

$xajax = new xajax();
$xajax->setFlag("debug", true);

// xajax mitteilen das registrierte Funktionen andere Antworten als nur xajaxResponse-Objekte zurückgeben dürfen
$xajax->setFlag('allowAllResponseTypes', true);

$xajax->registerFunction("testXmlResponse");
$xajax->registerFunction("testTextResponse");

$xajax->processRequest();

Als nächstes wird eine 'responseProcessor'-Javascriptfunktion zur Verfügung gestellt. Diese Funktion wird den Inhalt der Antwort auslesen und verarbeiten.

<script type='text/javascript'>

// Funktion um ajax Antwort-Textdaten zu verarbeiten
function textResponse(objResponse, objOptions)
{
	xajax.$('DataDiv').innerHTML = objResponse.responseText;
	xajax.completeResponse(objOptions);
}
// Function um ajax Antwort-XML-Daten zu verarbeiten
function xmlResponse(objResponse, objOptions)
{
	alert(objResponse.responseXML.documentElement.nodeName);
	xajax.$('DataDiv').innerHTML = 'non xajax: XML response';
	xajax.completeResponse(objOptions);
}
</script>

Zu guter letzt definiert man den Antwortverarbeiter im xajax.call

<input type="button" value="xml" 
onclick="xajax.call('testXmlResponse', {responseProcessor: xmlResponse}); return false;" />

<input type="button" value="text" 
onclick="xajax.call('testTextResponse', {responseProcessor: textResponse}); return false;" />


[edit] Abort Request on Timeout

In previous versions, xajax request calls would remain open until either the xajax response was received or the browser timed-out and aborted the call. Now, you can have xajax abort the request at an earlier time by setting a global abort timeout duration, or by creating a local callback event object and setting it's abort timeout duration. By setting the global abort timeout duration, you instruct xajax to abort all requests that exceed the specified duration. By using a local callback event, you can instruct xajax to abort specific requests at the specified duration.

[edit] Usage

// set delay event timeout to 400ms (.4 seconds)
// set delay abort timeout to 10000ms (10 seconds)
var myLocalCallback = xajax.callback.create(400, 10000);

xajax.call('myFunction', {callback: myLocalCallback});

Additionally, you can specify a Javascript function to call once the request has been aborted by xajax.

myLocalCallback.onExpiration = function() {
    // do something useful here
}
xajax.call('myFunction', {callback: myLocalCallback});


[edit] Improved Debug Output

The xajax debugger now shows some statistics about the request and response. Note in the sample below, the size of the request data is 35 bytes, the server response was code 200 (ok), the response data was 135 bytes and the request took 78 milliseconds total.

The timing will vary greatly, since it includes the time it takes to send the request, process the request, receive the response and process the response. If an alert box is shown during the response processing, this will delay the completion of the request, therefore the timing shown will depend also on the time it takes the user to respond to the alert.

xajax debug output
Tue Nov 28 2006 08:14:15 GMT-0500 (Eastern Standard Time)Done [78ms]
Tue Nov 28 2006 08:14:15 GMT-0500 (Eastern Standard Time)Received [status: 200, size: 135 bytes]:
<?xml version="1.0" encoding="utf-8" ?><xjx><cmd n="css">css1.css</cmd>
<cmd n="as" t="outputDIV" p="innerHTML">CSS1 loaded.</cmd></xjx>
Tue Nov 28 2006 08:14:15 GMT-0500 (Eastern Standard Time)Sent [35 bytes]
Tue Nov 28 2006 08:14:15 GMT-0500 (Eastern Standard Time)Sending request.
Tue Nov 28 2006 08:14:15 GMT-0500 (Eastern Standard Time)Initializing Request Object..
Tue Nov 28 2006 08:14:15 GMT-0500 (Eastern Standard Time)Calling loadCSS1 uri=css.php 
(post: xajax=loadCSS1&xajaxr=1164719655718)
Tue Nov 28 2006 08:14:15 GMT-0500 (Eastern Standard Time)Starting xajax...


[edit] Loading and unloading of CSS files

Minor improvements have been to the CSS handling in xajax 0.5 beta 2. In xajax 0.5 beta 1, the inclusion of CSS files was added. In beta 2, the ability to remove them was implemented. You can now add and remove style sheets at will. In addition, while including new CSS files, it may be desirable to wait for the CSS files to finish loading before concluding the xajax request. This is made possible with the $objResponse->waitForCSS(); response command.

This example shows the various calls:

function loadCSS1() {
	global $objResponse;
	$objResponse->removeCSS('css2.css');
	$objResponse->includeCSS('css1.css');
	$objResponse->waitForCSS();
	return $objResponse;
}


[edit] waitFor response command

A new response command was recently added which allows you to insert a wait state into the response processing. You can specify a javascript expression, which must evaluate to true or false, which will cause the response processing to wait for the expression to evaluate to true (or to timeout).

In the current implementation it is not possible to use this feature to synchronize between two xajax requests (since all response commands are processed in the order they are received). However, this feature can be used to watch for a javascript event to occur. Future versions may allow for request synchronization.

An example of how this feature might be used is shown below:

(test.php)

function test() {
    $objResponse = new xajaxResponse();
    $objResponse->includeScriptOnce('test.js');
    $objResponse->waitFor('testLoaded == true');
    return $objResponse;
}

(test.js)

myFunction = function() {
  // should do something useful here
}

testLoaded = true;

[edit] setFunction Response Command

You can now create functions on the browser side using a xajax response command. The setFunction command helps to automate the construction of javascript functions.

This:

$objResponse->setFunction("myFunction", "foo, bar", "alert(foo * bar);");

produces this:

myFunction = function(foo, bar) {
    alert(foo * bar);
}

[edit] wrapFunction Response Command

In addition to the setFunction command, you can also wrap an existing function inside another NEW function with the same name. Effectively, this wraps new statements around the function, then saves the result as a function with the same name.

Using this:

$objResponse->wrapFunction("myFunction", "foo, bar", 
    "alert('about to multiply ' + foo + ' and ' + bar);", 
    "alert('finished multiplication of ' + foo + ' and ' + bar);");

produces the following:

myFunction = function(foo, bar) {
    alert('about to multiply ' + foo + ' and ' + bar);
    original_myFunction(foo, bar);
    alert('finished multiplication of ' + foo + ' and ' + bar);
}

[edit] Script Context

Maintain the context for xajax asynchronous calls as if they were synchronous. You can now pass an object as a parameter to the xajax request and then access that object from the server side using the ->script, ->call, ->waitFor, ->setFunction and ->wrapFunction response commands.

In addition, you can access the context object in the callback event handlers.

In the example below, you can see an example of a xajax call that sets the context (which is a javascript object containing a reference to a button element and a div element. (javascript)

xajax.$('btn_100').onclick = function() {
    xajax.call('enable', { context : { btn: this, panel: xajax.$('div_100') } } );
}

In the example below, you can see how the context (referenced by 'this') can be modified using server commands. (php)

function enable() {
    $objResponse = new xajaxResponse();
    $objResponse->script("this.btn.innerHTML = 'Disable';");
    $objResponse->script("this.panel.visibility = 'visible';");
    $objResponse->script("this.panel.display = 'block';");
    return $objResponse;
}

In the script below, you can see how the context can be accessed from a callback event handler. (javascript)

xajax.callback.global.onComplete = function(oRequest) {
    alert(oRequest.context.btn.innerHTML);
}
  • Author: CtC - Joseph Woolley - 2007/01/01