Ajax implements page loading and content deletion, and ajax implements page loading
The biggest advantage of ajax is that it does not jump to pages during loading or deletion. Most of the current web pages are written using ajax, which reduces the amount of code compared to embedded PHP code, loading the page will also be faster,
The following describes how to use ajax to delete pages and fruits written in the database fruit table as an example. It may be easy to use ajax at first, so it should be a good exercise.
This is the fruit table.
The following is the homepage code. First, create a php file main. php.
1 <body> 2 3
I chose to display only the fruit name Price and origin columns in the fruit table on the page. Next we will write the loading processing page and create a php file named jiazaiym. php.
1 <? Php 2 include ("DADB. class. php "); 3 $ db = new DADB (); 4 $ SQL =" select * from fruit "; 5 $ arr = $ db-> Query ($ SQL ); 6 $ str = ""; 7 foreach ($ arr as $ v) 8 {9 $ str = $ str. implode ("^", $ v ). "|"; // use "|" to connect each row. In this way, an extra "|" 10} 11 $ str = substr ($ str, 0, strlen ($ str)-1); // delete 12 echo $ str; 13?>
After loading the Page code, you can officially write ajax, which should be written in main. php.
1 <script type = "text/javascript"> 2 $. ajax ({3 url: "jiazaiym. php ", 4 dataType:" TEXT ", 5 success: function (data) {6 var str =" "; 7 var hang = data. split ("|"); 8 9 for (var I = 0; I
Note: When writing ajax, pay special attention to the semicolons and commas in them. I write them as semicolons and the results cannot be output. After checking that the code is correct, this is a headache.
After loading the page, we need to start writing and deleting the page and create a php file shanchu. php. Deleting the page is very simple and similar to embedding php directly.
1 <?php 2 $ids=$_POST["ids"]; 3 include("DADB.class.php"); 4 $db=new DADB(); 5 $sql="delete from fruit where ids={$ids}"; 6 if($db->Query($sql,0)) 7 { 8 echo"OK"; 9 }10 else{11 echo"flase";12 }
Next, when I want to re-write an ajax file, I will find that the file is not run after it is written, because the class in the file is not recognized when the page is loaded, in this case, I need to put the deletion in the loaded ajax file and encapsulate the loading as a method. When deleting the file, I can call it once.
1 <script type = "text/javascript"> 2 Load (); 3 function Load () {4 $. ajax ({5 url: "jiazaiym. php ", 6 dataType:" TEXT ", 7 success: function (data) {8 var str =" "; 9 var hang = data. split ("|"); 10 11 for (var I = 0; I
In this way, there is no problem.