PHP and Ajax love to Kill

Source: Internet
Author: User

Learning directory: Ajax basic PHP and AJAX JSON format jquery in the Ajax

Personal site link Address: Deficiencies, welcome message ... Escape... 1.AJAX Foundation

(1) AJAX (Asynchronous JavaScript and XML): Asynchronous JavaScript and XML abbreviations.

(2) Ajax is not a programming language, but a technique for updating parts of a Web page without having to load the entire page.

(3) Disadvantages of traditional Web pages: You need to update the content or submit a form, you need to reload the entire page; with Ajax benefits: by using a small amount of data exchange in the background with the server, the Web page can implement asynchronous local updates. There is a very good user experience for filling out complex forms.

(4) Ajax synchronization and Asynchrony: Synchronization simply means loading the entire page; asynchronous can load part of the page. Specifically, the client is connected to the server side. Prior to the advent of Ajax technology, the exchange of data is synchronized, if the more complex form of filling will be very troublesome. With the XMLHttpRequest object, the synchronized world becomes the asynchronous world. This object can be exchanged with the server in the background by XMLHttpRequest.

(5) XMLHttpRequest object creation: Var requerst=new xmlhttprequest (), directly instantiate the Object! Note: IE5 and IE6 do not support this definition, and if you want to implement browser page compatibility, the following code shows:

var request;
if (window. XMLHttpRequest) {
    request  = new XMLHttpRequest ();  Ie7+,firefox,chrome,opera,safari ...
} else{
    request = new Activeobject ("Microsoft.XMLHTTP");//Ie6,ie5
}

(6) HTTP request: HTTP is a stateless protocol: a protocol that is not able to establish a persistent connection without memory. Further: through the page request and response process, the implementation of Web page debugging.

(6.1) A complete HTTP request process, usually has the following 7 steps: Establish a TCP connection Web browser send request command to Web server Web browser send request header information Web server answer Web server send answer header information Web server send data to browser The Web server shuts down the TCP connection

(6.2) HTTP requests generally consist of four parts: HTTP request method or action, such as a GET or POST request is requesting the URL, always know what the request address is the request header, contains some client environment information, authentication information, such as request body, that is, request body, The request body can contain customer-submitted queries to pay for wear information, form information, etc.

(6.3) Get and post [collects the name value from the form method= ' post/get]

To be honest, it's all about collecting values from the form. Pass the value of the past, one in the form of a URL (unsafe), a value in the form of display (security); Get is generally used for the acquisition of information, using the URL to pass parameters , limited to 2000 characters, visible to all people, unsafe. Post is typically used to send data from a form , with parameters in the HTTP request body, without limiting the number of messages sent.

(6.4) HTTP responses are typically made up of three parts: a status code consisting of a number and text that shows whether the request was successful or failed; the response header, which contains the server type, date time, content type and length, and the response body, which is the response body.

(6.5) The HTTP status code consists of three digits, where the first digit defines the type of status code: 1XX: The information class, which means that a Web browser request is received and is being further processed; 2XX: successful, indicating that the user request is properly received, understood, and processed, for example: OK 3XX: Redirect, Indicates that the request was unsuccessful and the customer must take further action 4XX: a client error, indicating that the client submitted a request with an error, such as 404 Not FOUND, which means that the document referenced in the request does not exist. 5XX: Server error, indicating that the server could not complete processing of the request.

(7) XMLHttpRequest Send Request: (Method of Object) open (Methods request method, URL request address, async request Synchronous or asynchronous (asynchronous is true, Sync is false, actually default is true));/// Call Asynchronous request Send (String);(when using the Get method, parameters can be left blank or null because the information is contained in the URL of the address bar, and must be filled in when the post is used;/ send the request to the server

Give me a chestnut:

Request.open ("POST", "create.php", true);
Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded")//Set HTTP header information to tell the Web server to send a form; Note: Setrequest request must be placed between open and send, otherwise it will throw an exception
request.send ("name= Wang &sex= male");

(8) XMLHttpRequest Gets the response: (object's methods and properties) ResponseText: simply: The receiving server responds to the loopback data. Gets the corresponding data in the form of a string. Responsxml: Gets the corresponding data in the form of XML. It is now generally converted to JSON-form data. Status and StatusText: Returns the HTTP status code in numbers and text. Getallresponseheader (): Gets all response headers. getResponseHeader (): Query the value of a field in the response.

ReadyState property: The response is notified when it returns to success. 0: The request was uninitialized and open has not been invoked. 1: The server connection has been established and open has been invoked. 2: The request has been received, that is, to receive the end of information. 3: Request processing, that is, received the response body. 4: The request is complete and the response is ready, that is, the response is complete.

Take a chestnut : Cover most of the Ajax content (typical XHR the process of building Ajax)

var request = new XMLHttpRequest ()///Create XHR Object
request.open ("Get", "get.php", true);//Invoke Asynchronous Request
request.send ();// Sends an asynchronous request
//listens to the event to determine whether the server is responding correctly
Request.onreadystatechange = function () {
  if request.readystate===4 && Request.status = = {
    request.reponsetext;//receiving server responds to loopback data
   }
}
2.PHP and Ajax

Actual combat: [Server-side and client] implement backend interface to query employees and new employees

(1) Client part code:

New Employee client code document.getElementById ("Save"). Onclick=function () {var request=new xmlhttprequest ();//Create XHR Object request . Open ("POST", "action.php"), or invoke the URL//document.getelementbyid ("Staffname") of the asynchronous request//data concatenation. Value gets the value written by the user in the form var d ATA = "Username=" + document.getElementById ("Staffname"). Value + "&num=" + document.getElementById (
    "Staffnumber"). Value + "&workname=" + document.getElementById ("Staffjob"). Value; Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");/Set HTTP header information Request.send (data);
            Sends an asynchronous request//listens to the event to determine if the server can respond correctly request.onreadystatechange=function () {if (request.readystate===4) { if (request.status===200) {//innerhtml can not only read element content, but also write content to elements//ajax engine objects through ResponseText properties Or the Responsexml property receives the data sent by the server and then processes it in a static page to make the page document.getElementById ("Createresult") to the local refresh effect. Innerhtml=re
            Quest.responsetext;
      }else{          Alter ("An error occurred:" +request.status);
 }
        }
    }
}

(2) server-side part of the code:

Query Employee server-side code
<?php 
Header (' Content-type:text/html;charset=utf8 ');
$con =mysqli_connect ("127.0.0.1", "" "," ");
mysqli_select_db ($con, "function");
$sql = "SELECT * from ' Ajax '";
$query =mysqli_query ($con, $sql);
The total number of data in the database is $number
$number =mysqli_num_rows ($query);
for ($i =0; $i < $number; $i + +) {
    //convert each data into associative array to print out
    $arr =mysqli_fetch_row ($query);
    Print_r ($arr);
    Echo $arr [2];d ie;
    if ($_get[' num ']== $arr [2]) {
        echo "finds employee: number $arr[2], name: $arr [1], Position: $arr [3]";
        break;
    }
 ? >
3.JSON Format

(1) Json:javascript object representation.

(2) JSON is the syntax for storing and exchanging text information, similar to XML. The use of key-value pairs of organization, easy to read and machine interpretation.

(3) JSON is language-independent, and any language can parse JSON, as long as the rules of JSON are in the line.

(4) JSON has a smaller length than XML; JSON reads and writes faster; JSON can be directly parsed using the JS built-in method, which is very convenient to convert to a JS object.

(5) JSON syntax rule: The writing format for JSON data is: name/value pairs .

The name in the combination of name/value is written in front (in double quotes), the value pair is written in the back (also in double quotes), separated by a colon, such as "name": "King Hammer". Note : JSON differs from JavaScript Object notation in that the key value of the JavaScript Object notation does not need to be quoted, but the key value of the JSON is quoted.

Note : JSON can be integral, floating-point, string (in double quotes), Boolean (True or False), array (in square brackets), objects (in curly braces), NULL, and other data types.

Give me a chestnut:

{//Defines a JSON object
  "staff": [//defines an array of
    {"name": "King Hammer", "Age": 21},//defines a name object
    {"name": "Beast", "Age": 35}
  ]
}

(6) JSON parsing: eval () and Json.parse () two ways to parse into JSON form

Comparison of two methods: it is recommended to use the Json.parse () method to parse into JSON form

eval (); If there is a function or JS program code in JSON (Alert or a window.location.href () Jump link virus web site, etc.), it will give priority to code execution and dangerous operation. Json.parse (); The JSON file has a checksum, if there is a program script in the JSON file, it resolves the error.

Give me a chestnut:

var jsondata= ' {"
    staff": [{"
            name": "King Hammer",
            "Age": "}",
        {
            "name": "Call Beast",
            "Age":
        },
        {
            "name": "Wang Nima",
            "Age":}
    ]
} ';

var jsonobj=json.parse (jsondata);//json.parse parsing json
var jsonobj=eval (' + Jsondata + ');//eval parsing json

alert (jsonobj.staff[0].name);

Note : The above writing is wrong, just to see clearly. Comma is not a separator, the comma is text content, all should be compact to write, not to see for themselves, the artificial use of space separate. (One-hour error was found here ...)

(7) JSON verification tool: Jsonlint

(8) Raise a chestnut:

Using JSON, you first need a server-side convention, which
can reduce more judgment, show
{
    //front-end rule validation, and back-end data validation "success" in more elegant form
    : true,//is executed correctly ( Form rules validation)
    "msg": "XXX"//Request Response value succeeded (information returned by HTTP response)
}

Server-side Partial code:

echo "parameter error, the employee information is not complete";
Echo ' {' success ': false, "MSG": "Parameter error, employee information not filled"};

if ($query) {
    //echo "employee:". $_post["username"]. "The information was saved successfully. ";
    Echo ' {' success ': true, ' msg ': ' Employee save Successful '} ';
} else{
    //echo "staff:" $_post["username". "Information save failed. ";
    Echo ' {' success ': false, ' msg ': ' Employee Save Failed '} ';
}

Client JSON code: Other invariant, converts the server-side response over the ResponseText (text form) to (JSON), converts the JSON string to a JSON object data, and then can process the data in the form of an object

    Request.onreadystatechange=function () {
        if (request.readystate===4) {
            if (request.status===200) {
                // Converts the server-side response responsetext (text form) to (JSON form)
                //Convert the JSON string to a JSON object data
                var data=json.parse ( Request.responsetext);
                if (data.success) {
                    document.getElementById ("Createresult"). innerhtml=data.msg;
                } else{
                    document.getElementById ("Createresult"). Innerhtml= "Error" +DATA.MSG;}}}
    
Ajax in the 4.jQuery

(1) Use jquery to implement AJAX requests: function: Avoid compatibility issues, code concise, easy to operate.

(2) Syntax: Jquery.ajax ([Settings]) Type: type, "POST" or "get", default to "get". URL: The address where the request is sent. Data: Is an object that is sent to the server, along with a request. DataType: Expected data type returned by the server. If not specified, jquery will automatically intelligently judge against the HTTP packet mime information, which we typically use in JSON format and can be set to "JSON". Success: is a method that requests a successful destroy function. Incoming data returned, and a string containing the success code. Error: is a method that calls this function when a request fails. Incoming XMLHttpRequest object.

Update Time: 2018/2/13 23:36:53

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.