[php] xajax 的表單輸入欄位(input、textarea)的處理教學

如果要使用xajax來處理input的資料,就如同使用php來處理一樣,其實是非常容易的。而以下就將介紹如何使用xajax來檢查用戶帳號和密碼是否有輸入。

首先,先看一下原始的程式碼如下:

  1. <?php
  2. include_once ("./xajax/xajax_core/xajax.inc.php");
  3. $xajax = new xajax();
  4. $xajax->registerFunction("processform");
  5.  
  6. function processform($form){
  7. $res = new xajaxResponse();
  8. $username = $form['username'];
  9. $password = $form['password'];
  10. $expr = $form['expr'];
  11. if (trim($username) == '')
  12. $res->assign("nousername", "innerHTML", "Please input a username");
  13. else
  14. $res->assign("nousername", "innerHTML", "");
  15.  
  16. if (trim($password) == '')
  17. $res->assign("nopassword", "innerHTML", "Please input a password");
  18. else
  19. $res->assign("nopassword", "innerHTML", "");
  20. $res->assign("expr", "innerHTML", $expr);
  21. return $res;
  22. }
  23.  
  24. $xajax->processRequest();
  25. ?>
  26. <html>
  27. <head>
  28. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  29. <?php
  30. $xajax->printJavascript("/xajax");
  31. ?>
  32. </head>
  33. <body>
  34. <form id="form1" action="javascript:void(null);">
  35. <div>username: <input type="text" name="username" /> <span id="nousername"></span></div>
  36. <div>password: <input type="password" name="password" /> <span id="nopassword"></span></div>
  37. <div>expr:
  38. <textarea name="expr" cols="45" rows="4"></textarea>
  39. <span id="expr"></span>
  40. </div>
  41. <input type="button" value="Click Me" onClick="xajax_processform(xajax.getFormValues('form1'));" />
  42. </form>
  43. </body>
  44. </html>

 

這段程式碼比較要注意的是表單的部份,其中「xajax.getFormValues(‘form1’)」是將我們表單的form1以參數傳送到「processform」這個函式。

  1. <form id="form1" action="javascript:void(null);">
    
  2. <div>username: <input type="text" name="username" /> <span id="nousername"></span></div>
    
  3. <div>password: <input type="password" name="password" /> <span id="nopassword"></span></div>
    
  4. <div>expr:
    
  5. <textarea name="expr" cols="45" rows="4"></textarea>
    
  6. <span id="expr"></span>
    
  7. </div>
    
  8. <input type="button" value="Click Me" onClick="xajax_processform(xajax.getFormValues('form1'));" />
    
  9. </form>

 

而如果要取出輸入欄位的值,只要用「$form[變數名稱]」就可以了,,以帳號和密碼而言,要去掉左右兩側的空白,並且進行檢查使用者是否有輸入值即可。

  1. $username = $form['username'];
  2. $password = $form['password'];
  3. $expr = $form['expr'];