趁今天有空,就学习了Ajax,在Ajax in action那本书里提到了SAjax,就去下来看看,果然功能强大,让编写Ajax代码变的很简单,于是就写了个“修改内容不刷新页面”的代码,这个功能在网上以前是到处看到,今天终于自己实现了个,代码里有了PHP5的DOM函数,由于这个Blog空间只支持PHP4,所以也就没法在这里运行了。
XML文件,代码从这个文件中读取并在修改后写入到该文件
- <?xml version="1.0"?>
- <test>
- <value>编辑文本</value>
- </test>
以下是代码:
- <?php
- require("Sajax.php");
-
-
- function showxml(){ //从test.xml读取,参考PHP DOM
- $doc=new DOMDocument();
- $doc->load("test.xml");
- $hello=$doc->getElementsByTagName("value")->item(0)->nodeValue;
- return $hello;
- }
-
- function changexml($text){ //写入到test.xml文件
- $doc=new DomDocument();
- $doc->load("test.xml");
- $doc->getElementsByTagName("value")->item(0)->nodeValue=$text;
- $doc->save("test.xml");
- $hello=$doc->getElementsByTagName("value")->item(0)->nodeValue;
- return $hello;
- }
-
- sajax_init();
- $sajax_debug_mode=0; //关闭调试信息
- sajax_export("showxml","changexml"); //sajax输出showxml,changexml两个js函数
- sajax_handle_client_request(); //sajax对客户端响应后的处理
-
- ?>
-
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
-
- <script language="javascript">
- <?php sajax_show_javascript(); ?> //sajax输出ajax代码及sajax_export的两个函数
-
- function show(text){
- document.getElementById("hello").innerHTML=text;
- }
-
- function showxml(text){
- x_showxml(text,show); //由sajax输出的showxml函数,默认在原函数名前加了"x_"
- }
-
- function changexml(text){
- x_changexml(text,show) //原PHP的changexml函数
-
- }
-
- var span,input;
-
- function edit(){
- span=document.getElementById("hello");
- input=document.createElement("input");
- input.setAttribute("type","text");
- input.setAttribute("id","input");
- input.setAttribute("value",span.innerHTML);
- document.body.replaceChild(input,span);
- }
-
- function save(){
- changexml(input.value);
- document.body.replaceChild(span,input);
- }
-
- </script>
-
- <title>sajax Test....</title>
- </head>
- <body onLoad="showxml()">
-
- <span id="hello" onClick="edit()">loading...</span>
- <p>点击上面的文本即可修改,实现不刷新页面修改内容并显示</p>
- <input type="button" name="hello" value="修改" onClick="save()">
-
-
- </body>
- </html>
Tags:
ajax,
dom,
JavaScript,
php,
Sajax,
xml