[Ajax] tutorial on TiZag

  • 1
Ajax tutorial on TiZag
概念: 直接在html裡嵌入一個Ajax function, 當有html物件要使用Ajax, 就直接呼叫這個function即可
Ajax tutorial on TiZag
概念: 直接在html裡嵌入一個Ajax function, 當有html物件要使用Ajax, 就直接呼叫這個function即可
Form:
      Using a special Javascript object XMLHttpRequest. With this object, your Javascript can get information from the server without having to load a new page!
Browser Support:
      Try three times to make our XMLHttpRequest object.
ajaxRequest = new XMLHttpRequest();

ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");>
xmlhttprequest object:
a. onreadystatechange stores the function that will process the response from the server.
b. readyState is 4 that means the response is complete and we can get our data.
c. For simple Ajax applications, you can retrieve the server's response by using the responseText property.
d. The URL is set using the open method, which takes three arguments. The second argument is the important one, as it is the URL of our PHP script.  這裡要寫一個簡單的php, 會在之後說明。(Assuming that the HTML and PHP files are in the same directory )
Server-side php object:
      The XMLHttpRequest property, responseText, will store the data that this PHP script displays to the browser, so all we want this script to do is Echo the current time (這份php code應該要跟此份html放在同一資料夾)
完整程式範例
(1) order.html
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!
      
        try{
                // Opera 8.0+, Firefox, Safari
                ajaxRequest = new XMLHttpRequest();
        } catch (e){
                // Internet Explorer Browsers
                try{
                        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try{
                                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e){
                                // Something went wrong
                                alert("Your browser broke!");
                                return false;
                        }
                }
        }
        
// Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                        document.myForm.time.value = ajaxRequest.responseText;
                }
        }
        ajaxRequest.open("GET", "serverTime.php", true);
        ajaxRequest.send(null);

}
//-->
</script>
<form name='myForm'>
Name: <input type='text'
onChange="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>
 
(2) serverTime.php
<?php
echo date("H:i:s");
?>


1 則留言 :