"PHP" uses native JavaScript ajax for the MVC layered Design of PHP, compatible with IE6

Source: Internet
Author: User

MVC is just a design pattern, once considered model 1, that is, the server statement and HTML statement is a mixture of PHP, in fact, without any framework, just use the original ecological JavaScript Ajax can also be MVC design. Since nothing is useful, the compatibility with IE6 is very strong. or "PHP" database additions and deletions and PHP and the interaction between JavaScript (click to open the link) that page, the database additions and deletions to change the content, I hope you can promote to the entire site.


I. BASIC OBJECTIVES

The entire Web page implementation effect is as follows, the user entered the form immediately after the effect.


Second, the basic idea

First of all, in the test database has a such user information table, when the table is built to check that the database field encoding is utf-8, some MySQL in the installation time did not change the default encoding Latin1, or a while you killed can not save Chinese.


Then, the entire Web page project structure is as follows:


Do not make any refresh in the view.php page, using the original JavaScript Ajax, directly complete the v-c layer of interaction. The interaction of C-M layer is introduced into the business logic class of M layer through the include statement, which is accomplished by passing the class parameters.

At the same time, the C, M layer of PHP refused to directly enter the URL access. This is not like JSP or asp,c layer, M layer are compiled Java files or C # files, simply can not access. We also need to protect it.



Third, the production process

1, the view layer on a simple view.php, its layout as follows, nothing to say, very simple HTML layout. Also, note that this page:

(1) The form is not set and all the form submissions are triggered by a button that triggers the corresponding JavaScript.

(2) The ID of each component, which is used in JavaScript for a while. The drop-down boxes for user information tables and modification IDs are loaded with the following script Ajax.

(3) Layout, including the script for a while without any PHP code, easy to layout. You change the suffix to. html will work as well. What is a real view layer? That's it, there's no server code.

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

In fact, the essence of the entire view layer lies in the following JavaScript script. The view layer does not need to use the Xajax plugin, "PHP" Xajax Helloworld "(Click to open the link). Write directly with native JavaScript. Although the code volume is more than the front-end framework such as jquery, it is not easy to remember. From building an Ajax object, setting up an AJAX request header, and working with Ajax text all on your own, but in the process of development, just copy and paste. So it can be observed that all of the Ajax interaction functions are small and easy. Take Foralluserinfo (); This function focuses on how the V-C layer interacts with Ajax.

<script>//First, this page is loaded with two functions to load. Foralluserinfo (); Fortotal ();//Create Ajax objects, different browsers have different methods of creation, in fact, this function is a simple new statement only. function Createxmlhttprequest (XMLHttpRequest) {var xmlhttprequest;if (window. XMLHttpRequest) {xmlhttprequest=new XMLHttpRequest ();} else if (window. ActiveXObject) {try{xmlhttprequest=new ActiveXObject ("Msxml2.xmlhttp");} catch (e) {xmlhttprequest=new ActiveXObject ("Microsoft.XMLHTTP");}} return XMLHttpRequest;} function Foralluserinfo () {var xmlhttprequest=createxmlhttprequest (XMLHttpRequest);//indicates the corresponding page var url= "dbselect.php"; Xmlhttprequest.open ("POST", url,true);//There is no explanation here, all your JavaScript requests are written like this, not garbled xmlhttprequest.setrequestheader (" Content-type "," application/x-www-form-urlencoded ");//For dbselect.php, this view.php does not have any parameters for you. Xmlhttprequest.send (null);//For returning the result how to deal with the problem xmlhttprequest.onreadystatechange=function () {//This 4 represents has been sent after the IF ( xmlhttprequest.readystate==4) {//200 representative correctly received the return result if (xmlhttprequest.status==200) {//Then the DIV with the ID of result, is the entire dbselect.php page. document.getElementById ("Result"). Innerhtml=xmlhttprequest.reSponsetext;} else{//If you can't accept the result properly, you must be off the net, or my server is off. Alert ("Network connection interrupted! ");}}};} function Fortotal () {var xmlhttprequest=createxmlhttprequest (XMLHttpRequest); var url= "dbtotal.php"; Xmlhttprequest.open ("POST", url,true); Xmlhttprequest.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); Xmlhttprequest.send (NULL); Xmlhttprequest.onreadystatechange=function () {if (xmlhttprequest.readystate==4) {if (xmlhttprequest.status==200) { var total=parseint (Xmlhttprequest.responsetext);//First empty the drop-down list of the change ID document.getElementById ("userid"). innerhtml= ""; if (total>0) {for (Var i=1;i<total+1;i++) {//javascript Increments the node procedure, the number of items in the database is populated with the number of IDs that are modified for the user. var selectnode=document.createelement ("option"); selectnode.value=i;selectnode.innerhtml=i; document.getElementById ("userid"). appendchild (Selectnode);}} Else{alert ("Network connection interrupted! ");}}};} function Insert () {//All forms var Username=document.getelementbyid ("username") that are taken from the input box to insert data. Value;var password= document.getElementById ("password"). value;//if the user enters a value that is not empty, the ajaxif is executed (username!= "&&password!=" "{var xmlhttprequest=createxmlhttprequest (XMLHttpRequest); var url= "dbinsert.php"; Xmlhttprequest.open ("POST", url,true); Xmlhttprequest.setrequestheader ("Content-type", "application/x-www-form-urlencoded");// Here the view layer's view.php needs to send two parameters to the controll Layer dbinsert.php processing xmlhttprequest.send ("Username=" +username+ "&password=" + password); Xmlhttprequest.onreadystatechange=function () {if (xmlhttprequest.readystate==4) {if (xmlhttprequest.status==200) {/ /Add data successfully, then partially refresh the view layer's user information table with the Change ID drop-down list foralluserinfo (); Fortotal ();} Else{alert ("Network connection interrupted! ");}}};} Else{alert ("must not be empty!") ");}} This modifies the data with the insert () Empathy function Update () {var Userid=document.getelementbyid ("userid"). Value;var rowname= document.getElementById ("RowName"). Value;var Rowtext=document.getelementbyid ("Rowtext"). Value;if (userid!= "" &&rowname!= "" &&rowtext!= "") {var xmlhttprequest=createxmlhttprequest (XMLHttpRequest); var url= " Dbupdate.php "; Xmlhttprequest.open ("POST", url,true); Xmlhttprequest.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); XmlhttPrequest.send ("userid=" +userid+ "&rowname=" +rowname+ "&rowtext=" +rowtext); Xmlhttprequest.onreadystatechange=function () {if (xmlhttprequest.readystate==4) {if (xmlhttprequest.status==200) { Foralluserinfo (); Fortotal ();} Else{alert ("Network connection interrupted! ");}}};} Else{alert ("must not be empty!") ");}} </script>

2, Controll Layer

The pages of the controll layer correspond to the JavaScript function one by one in the view layer.

For example, dbupdate.php corresponds to the update () function in view.php. Correspond by the following two sentences.

var url= "dbupdate.php"; Xmlhttprequest.open ("POST", url,true);
(1) dbupdate.php

Very simple page, get the front end sent over two data, then to the model layer of interaction, complete the operation of the database. Modify the database, the database will not return any results, so there is no data to the front-end. If you do not get the front end of the parameters sent, it must be a malicious user, by entering the URL is not normal to open this page. The C layer m layer is generally not open to you.

<?phpinclude_once ("db.php"), if (Empty ($_request["userid")) {header ("content-type:text/html; Charset=utf-8 "); echo "Please open this page normally!" ";} else{$db =new db (), $userid =$_request["userid"]; $rowname =$_request["RowName"]; $rowtext =$_request["Rowtext"; $db- >modify ("Update user set". $rowname. " = ' ". $rowtext." ' Where id= '. $userid. ";"); >

(2) dbinsert.php

Insert the data the same reason, no longer repeat. The insert () function corresponding to the front end

<?phpinclude_once ("db.php"), if (Empty ($_request["username")) {header ("content-type:text/html; Charset=utf-8 "); echo "Please open this page normally!" ";} else{$db =new db (), $username =$_request["username"]; $password =$_request["password"]; $db->modify ("INSERT INTO User (Username,password) VALUES (' ". $username." ', ' ". $password." '); ");}? >
(3) dbtotal.php

This page is used to query the database of how many results, we modify the data drop-down list to provide users with the number of IDs, to specify the user changes.

Corresponds to the Fortotal () function in view.php. This page has a return result. So dbtotal.php the result with echo print, the front end through:

var total=parseint (Xmlhttprequest.responsetext);
In this sentence, the xmlhttprequest.responsetext gets, the front-end JavaScript must be forced to indicate that this is a number, or else there will be 7+1=71 God operation. JavaScript has no way of taking numbers as strings, after all, all variables are var. PHP is $ $.

This page does not need to be protected, after all, certainly to the user to see.

<?phpinclude_once ("db.php"), $db =new db (), $total = $db->gettotal (); Echo $total;? >
(4) dbselect.php

This page is actually the same as dbtotal.php, but it becomes a form that gives the front-end view.php Foralluserinfo (). Foralluserinfo () Gets the data in fact a piece of HTML text, directly through. innerHTML put it on.

<?phpinclude_once ("db.php"); $db =new db (); $user = $db->getalluserinfo (); ><table border= "1" ><tr><th>ID</th><th> User name </th><th> password </th> </tr><?phpfor ($i =0; $i <count ($user); $i + +) {echo "<tr><td>". $user [$i] [' ID ']. " </td><td> ". $user [$i] [' username ']." </td><td> ". $user [$i] [' Password ']." </td></tr> ";}? ></table>

This page has HTML to die can not be mixed with the PHP code of the obsessive-compulsive patients, please do all the HTML code, give the echo output, anyway, I can only give such a solution.


3. Model Layer

All the methods in this layer correspond to the pages of the C layer.

First, a database connection function is common. They are then called in the method, and the connection is closed when each query is completed.

You can then notice the dbupdate.php of the controll layer above and dbinsert.php a method that is common to this class. This is mostly due to the passing of an SQL statement, and then not returning the result, so it can be combined. and the query database of all the data and the query database the number of data returned is different, so separate two methods.

<?phpfunction Createcon () {///database address is localhost:3306, database user name (second item) is root, database password (third item) is Root$con=mysql_connect (" LocalHost "," root "," root "), if (! $con) {die (" Connection failed! ");} To manipulate the test database mysql_select_db ("test", $con);//Prevent garbled mysql_query ("Set names UTF8;"); return $con;} Class Db{public function Getalluserinfo () {$con =createcon (); $result =mysql_query ("select * from User;"); /If the query results in many, put in a two-dimensional array inside, return to the Controll layer//controll layer and then the two-dimensional array one by one processing. Does starting this two-dimensional array correspond to the ArrayList in the JSP? ^_^ $userList =array (); for ($i =0; $row =mysql_fetch_array ($result); $i + +) {$userList [$i] [' ID ']= $row [' id ']; $userList [$ i][' username ']= $row [' username ']; $userList [$i] [' Password ']= $row [' Password '];} Mysql_close ($con); return $userList;} Public Function Gettotal () {$con =createcon (), $result =mysql_query ("SELECT count (*) as total from user;"); /If the return result is only one, then fetch the data directly. $row =mysql_fetch_array ($result); Mysql_close ($con); return $row [' Total '];} Public function Modify ($sql) {//For those methods that pass SQL to return no results, generalize to the same class $con=createcon (); mysql_query ($sql); Mysql_close ($con);}}? >

Iv. Summary and Prospect

The above production process best together to see, anyway, I can only be layered. V-c,c-m has been interacting, never being cut off, and not stopping at all. Compare with "PHP" database additions and deletions and PHP and JavaScript interaction (click to open the link) This works in MODEL1 mode, although the number of pages increased, but the module is more clear.

Anyway, MVC is just a design pattern, design ideas, also can be implemented in PHP. In JSP the boast of this mode is exaggerated, mainly the JSP of some creators, constantly on the use of the framework, and forget the essence of the language.

I think this example proves once again that language is only the carrier of thought expression. No plugin without frame, pure html+css and pure JavaScript plus PHP can be implemented, compatible with IE6. If you pack the same, put on the anti-injection function, you can completely become your own framework.

Compared with the JSP and ASP, I write php more comfortable, farewell to Myeclipse/eclipse and Visual Studio explosion, with a long time has been approved a hair is not dreamwaver, even can be written in Notepad page, the slightest card. A WinXP of garbage can create a good website. The key is your language basic problem. Do less spray, do a little more work. Multi-touch several programming languages.

"PHP" uses native JavaScript ajax for the MVC layered Design of PHP, compatible with IE6

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.