Front-end development--ajax

Source: Internet
Author: User

With Ajax, he has two modules, one client and one server.

The client is responsible for sending the data, sending the data in two ways, one is get and the other is post.

The server is the data that is used to receive, process, and send requests.

To use Ajax, you have to create an Ajax object function:

var request = new XMLHttpRequest ();
Request.open ("Get/post", "Address of the server", "False/true");
Request.send ();

The third parameter is used to set whether or not to process asynchronously.

If you are a GET method, your server address also includes the information you send, separated by the?

Request.open ("GET", "server.php?number=" + document.getElementById ("keyword"). value);

If you are the POST request mode, you can directly write your server address, can be an absolute address, can be a relative address, but you want to put the requested data into a variable, and then sent through the way of Send (Var), such as:

var request = new XMLHttpRequest ();
Request.open ("POST", "server.php");
var data = "Name=" + document.getElementById ("Staffname"). Value
+ "&number=" + document.getElementById ("Staffnumber"). Value
+ "&sex=" + document.getElementById ("Staffsex"). Value
+ "&job=" + document.getElementById ("Staffjob"). Value;
Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
Request.send (data);

This allows simple data requests to be sent out.

--------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------

The next step is to get the data request sent out:

You want to know how to get the request data you have to know the entire data sent, waiting for the server response, processing process, here I am lazy I will not introduce.

I'll tell you what, XMLHttpRequest got a reaction.

Case:

Request.onreadystatechange = function () {
if (request.readystate===4) {
if (request.status===200) {
document.getElementById ("SearchResult"). InnerHTML = Request.responsetext;
} else {
Alert ("Error occurred:" + request.status);
}
}
}

Let's take a concrete example to achieve this:

Service side:

<! DOCTYPE html>


<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>Demo</title>
<style>
Body, input, select, button, H1 {
font-size:28px;
line-height:1.7;
}
</style>

<body>

<label> Enter your employee number:</label>
<input type= "text" id= "keyword"/>
<button id= "Search" > Inquiries </button>
<p id= "SearchResult" ></p>


<label> Enter employee Name: </ Label>
<input type= "text" id= "Staffname"/><BR>
<label > Please enter employee number: </LABEL>
<input type= "text" id= "Staffnumber"/><BR>
<label> Please select employee Gender: </label>
<select id= "Staffsex";
<option> female </option>
<option> male </option>
</select><br>
<label> Please enter the position of the employee: </label>
<input type= "text" id= "Staffjob"/><br>
<button id= "Save" > Save </button>
<p id= "Createresult" > </p>

<script>
document.getElementById ("Search"). onclick = function () {
var request = new XMLHttpRequest ();
Request.open ("GET", "server.php?number=" + document.getElementById ("keyword"). value);
Request.send ();
Request.onreadystatechange = function () {
if (request.readystate===4) {
if (request.status===200) {
document.getElementById ("SearchResult"). InnerHTML = Request.responsetext;
} else {
Alert ("Error occurred:" + request.status);
}
}
}
}

document.getElementById ("Save"). onclick = function () {
var request = new XMLHttpRequest ();
Request.open ("POST", "server.php");
var data = "Name=" + document.getElementById ("Staffname"). Value
+ "&number=" + document.getElementById ("Staffnumber"). Value
+ "&sex=" + document.getElementById ("Staffsex"). Value
+ "&job=" + document.getElementById ("Staffjob"). Value;
Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
request.send (data);
Request.onreadystatechange = function () {
if (request.readystate===4) {
if (request.status===200) {
document.getElementById ("Createresult"). InnerHTML = Request.responsetext;
} else {
alert ("Error occurred:" + request.status);
}
}
}
}
</script>
</body>

Service side:

<?php
Set page content is HTML encoded format is UTF-8
Header ("Content-type:text/plain;charset=utf-8");
Header ("Content-type:application/json;charset=utf-8");
Header ("Content-type:text/xml;charset=utf-8");
Header ("Content-type:text/html;charset=utf-8");
Header ("Content-type:application/javascript;charset=utf-8");

Defines a multidimensional array that contains information about employees, each employee information as an array
$staff = array
(
Array ("name" = "Hong Qi", "number" = "101", "sex" = "male", "job" and "General manager"),
Array ("name" = "Guo Jing", "number" = "102", "sex" = "male", "job" and "Development Engineer"),
Array ("name" = "Huang Rong", "number" = "103", "sex" = "female", "job" and "Product Manager")
);

Determine if a GET request is being searched, and if it is a POST request, create a new
$_server is a hyper-global variable that is available in all scopes of a script without using the Global keyword
$_server["Request_method"] returns the request method used by the access page
if ($_server["request_method"] = = "GET") {
Search ();
} elseif ($_server["request_method"] = = "POST") {
Create ();
}

//Search for employees by employee number
function Search () {
//Check if there is an employee number parameter
//isset The detection variable is set; empty determines whether the value is null
//Hyper Global variables $_get and $_post for collecting form data
if (!isset ($_get["number"]) | | empty ($_get["number"])) {
echo "parameter error";
return;
}
variables declared outside the//function have Global scope and can only be accessed outside of the function.
//global keyword for accessing global variables within a function
Global $staff;
//Get number parameter
$number = $_get["number"];
$result = "No employees found. ";

//Traverse the $staff multidimensional array to find out if an employee with a key value of number exists, and if so, modify the return result
foreach ($staff as $value) {
if ($value ["number"] = = $number) {
$result = "Find Employee: Employee number:". $value ["No."]. ", Employee Name:". $value ["Name"].
", Employee Gender:". $value ["Sex"]. ", Employee Position:". $value ["Job"];
Break ;
}
}
echo $result;
}

Create an employee
function Create () {
Determine if the information is fully filled
if (!isset ($_post["name"]) | | empty ($_post["name"])
|| !isset ($_post["number"]) | | Empty ($_post["number"])
|| !isset ($_post["Sex"]) | | Empty ($_post["sex"])
|| !isset ($_post["job"]) | | Empty ($_post["job"])) {
echo "parameter error, employee information is not complete";
Return
}
TODO: Get post form data and save to database

Prompt to save successfully
echo "Employees:". $_post["Name"]. "Information saved successfully!" ";
}

Front-end development--ajax

Related Article

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.