你的位置:HBcms宏博内容管理系统 PHP技术 正文
PHP技术
  1. 专用主机
内容搜索
热门内容
  1. PHP官方网站,php官方..
  2. 建网站需要多少钱? 建..
  3. PHP ASP比较:PHP比AS..
  4. PHP6下载,php6介绍和..
  5. php程序员前途,mysql..
  6. 宏博cms和北京易体验合..
  7. SMTP判断邮箱是否存在..
  8. PHP生成静态页面详解
  9. 用PHP与XML进行网站编..
  10. 美国Hostmonster虚拟主..
推荐内容
  1. PHP官方网站,php官方..
  2. 把握商机:免费成为 H..
  3. 用PHP与XML进行网站编..
  4. [转]PHP突出开源优势要..
  5. 在线操作系统----TOMO..
  6. 用PHP实现验证码功能
  7. PHP生成静态页面详解
  8. 宏博cms和北京易体验合..
  9. Linux服务器php虚拟主..
  10. php程序员前途,mysql..
AJAX Hello World with HTML_AJAX(PHP的PEAR::HTML_AJAX类库应用)
  • 原作者:hbcms 添加时间:2007-05-26 发表时间:2007-05-26 人气:1874
  • 本文章共6540字,分2页,当前第2页,快速翻页:
  • AJAX Hello World with HTML_AJAX

    This is a continuation of my AJAX Hello World series, in my earlier posts I covered sajax and JPSpan. In this article i’ll cover how to get a basic AJAX appliction up and running with HTML_AJAX. If you haven’t figured it out yet im one of the author’s of HTML_AJAX. The application in question is the same simple app as the other examples, it has an input box for adding random strings and an button to add a random one to a div.

    When your using HTML_AJAX you have more choices then with either JPSpan or sajax. But to keeps things simple were going to use a setup similar to how we used JPSpan, an external server page that generates a JavaScript proxy which is included by our html page that does the actual action. HTML_AJAX could also be used sajax style with the proxy and server code generated inline, but I don’t recommend this usage since it remove your ability to cache the generated JavaScript.

    Installing HTML_AJAX

    This is nice and simple its simply:
    pear install HTML_AJAX-alpha
    If you don’t have pear setup on your server just follow the installation instructions in the PEAR Manual.

    Setting up the Server Component

    An HTML_AJAX server page is generally very simple, it creates an HTML_AJAX_Server instance, registers all the classes you want exported and handles incoming requests. The incoming requests can be three different types:

    • Client library request: query string includes ?client=all (can also be each of the seperate component parts)
    • Generated stub requests: query strings includes ?stub=classname (all keyword can also be used)
    • AJAX Requests: query string includes ?c=classname&m=methodname

    Client and Stub requests can be combined into the same one, but remember there is a tradeoff when doing that. You’ll have less roundtrips to the server but generated stubs are more likely to change so they can hurt your cacheability. You also want to be careful about using stub=all since the stub for 10 different classes can be quite large. The next release will also allow for combining multiple classes in a stub request by seperating them with a comma like so: stub=test,test2. Finally a note on class names, in php4 they will be lower case since thats what PHP returns, if you would like to have case or need to guarantee php4/5 compatability you’ll want to use some optional paramaters to registerClass, the first is the name to register the class in JavaScript as, the second is an array of methods to export.
    A basic server is shown below.

    <?php
    
    session_start();
    
    require_once ‘HTML/AJAX/Server.php’;
    require_once ‘HelloWorld.class.php’;
    
    $server = new HTML_AJAX_Server();
    
    $hello = new HelloWorld();
    $server->registerClass($hello);
    
    $server->handleRequest();
    
    ?>

    A server like this works fine for small scale projects, but it might not be a good choice for something larger since you could be creating 20 class instances just to serve a request on one of them. Any custom setup also has to be done for each class. HTML_AJAX provides a way to manage this by extending the server class and adding an init method for each class. A server that does this for the same HelloWorld class is shown below.

    <?php
    
    session_start();
    
    require_once ‘HTML/AJAX/Server.php’;
    
    class AutoServer extends HTML_AJAX_Server {
            // this flag must be set for your init methods to be used
            var $initMethods = true;
    
            // init method for my hello world class
            function initHelloWorld() {
                    require_once ‘HelloWorld.class.php’;
                    $hello = new HelloWorld();
                    $this->registerClass($hello);
            }
    
    }
    
    $server = new AutoServer();
    $server->handleRequest();
    
    ?>

    PHP Application Code

    In the server examples above you’ll notice were including a Hello World class. This hasn’t changed from the JPSpan example. The only thing of note is that makes heavy use of session, many AJAX apps will share this same heavy use, so make sure your server setups can handle that.

    <?php
    
    // our hello world class
    class HelloWorld {
    
            function HelloWorld() {
                    if (!isset($_SESSION[’strings’])) {
                            $_SESSION[’strings’] = array(‘Hello’,‘World’,‘Hello World’);
                    }
            }
    
            function addString($string) {
                    $_SESSION[’strings’][] = $string;
                    return $this->stringCount();
            }
    
            function randomString() {
                    $index = rand(0,count($_SESSION[’strings’])-1);
                    return $_SESSION[’strings’][$index];
            }
    
            function stringCount() {
                    return count($_SESSION[’strings’]);
            }
    }
    
    ?>

    The HTML that ties it all together

    To finish up our app we need to create the HTML that ties it all together. This is going to have two main parts, the main JavaScript logic, callback function for our async requests and a fake form. The call the form fake, because there is no form tags, were just powering everything off onclick event handlers on buttons. At some point in the future HTML_AJAX will support taking a normal form and magically turning it into an AJAX one but for now that thought is just in my head.

    The page starts with normal HTML boiler plate and an include of our client library and the stub hello world class. They are done all in a single class since that makes sense for this example, if I had 10 classes it wouldn’t.

    
    <html>
    <head>
            <title>HTML_AJAX Hello World</title>
            <script type=’text/javascript’ src=’auto_server.php?client=all&stub=helloworld’></script>
    </head></html>

    Next we build the callback hash, it has a method for each method in PHP, they will be called from the results from an async AJAX call. In this example each call back is really simple it either updates an element using innerHTML or appends to one. You could also use a normal JavaScript class instead of a hash, but thats only useful if you need multiple instances.

    
    var hwCallback = {
                    randomstring: function(result) {
                            document.getElementById(‘canvas’).innerHTML += ‘
    
    ‘+result+;
                    },
                    stringcount: function(result) {
                            document.getElementById(‘count’).innerHTML = result;
                    },
                    addstring: function(result) {
                            document.getElementById(‘count’).innerHTML = result;
                    }
            }
    

    The next step is to create an instance of our helloworld class and create a helper function. When we create an instance of our proxy class we pass in our callback, if we didn’t the instance would work in a sync manner, which can be useful, but in this case would make for a choppy ui. The helper function do_addString isn’t anything exciting, it just clears out the textbox after we’ve submited its current value.

    
            var remoteHW = new helloworld(hwCallback);
    
            function do_addString() {
                    remoteHW.addstring(document.getElementById(’string’).value);
                    document.getElementById(’string’).value = ;
            }
    

    Finally we have the html body of the page, it contains our buttons with onclick event handlers that call remote functions. It also contains our output divs.

    
    <body onLoad="remoteHW.stringcount()">
    
            <input type="button" name="check" value="Show Random String" onclick="remoteHW.randomstring(); return false;"/>
            <div>Number of Random Strings: <span id="count"></span></div>
            <div id="canvas" style="border: solid 1px black; margin: 1em; padding: 1em;"></div>
    
            <div>
            Add new String:
            <input type="text" name="string" id="string" size="20"/>
            <input type="button" name="check" value="Add new String" onclick="do_addString(); return false;"/>
            </div>
    </body>
    

    Trying out the sample

    If you got this far you’ll want to try out the Hello World app were building. If you compare it against the JPSpan or sajax version you won’t notice many differences. The only visual one that should show up is loading notice in the top right corner. Since providing user feedback is such an important part of making a usable AJAX application HTML_AJAX includes this basic loading symbol out of the box. If you just want to customize its looks you just need to create an element with the id of HTML_AJAX_LOADING. Its shown by setting its display style to block, and hidden by setting display to none everything else is left up to you so make sure to take care of any positioning and setting its display to none so its hidden by default. If you want to do somthing more complex you can override HTML_AJAX.onOpen and HTML_AJAX.onLoad check out the current methods to see hows its done.

    Finally you might notice some JavaScript errors if you try to make a lot of quick requests, like JPSpan HTML_AJAX only provides for one concurrent request at a time. This will change in the future giving you a number of different options but for now you can either keep those from happening at the application level, or just add a error handling function to HTML_AJAX.onError and ignore the call in progress ones.

    You can also download the project and try it out on your own server, its available as a tar.gz or a zip.

    Where to go from here

    Now that you’ve had a look at HTML_AJAX you might be wondering how to learn more about it. For the moment your options are pretty limited. You can check out the examples dir (in the docs dir in pear or online) or you can ask questions on this post. You might also find the source to be useful, for now the newest version lives on my svn server.

    Feed back is appreciated as I’ll use that to decide what features to add to HTML_AJAX and what to fully document next, feel free to post comments or trackbacks even if you have a lot to say.

    Update:
    This example won’t work correctly in PHP5 since the methods will be exported with CASE, take a look at the generated JavaScript if you don’t understand what i mean (auto_server.php?clalss=helloworld). See Comment #40 for your options to fix things.

  • 点这里复制本页地址发送给您QQ/MSN上的好友
  • 相关文章
  • 相关评论
  • 本文章所属分类:首页 PHP技术