About AJAX mates JSON array implementation no refresh

Source: Internet
Author: User

1 Create a new text.html page

<!doctype html>

<meta charset=gb2312 ">

<title></title>

<script type= "Text/javascript" >

Window.onload=function () {

document.getElementById (' Search '). Onclick=function () {

var request=new xmlhttprequest ()//There is no judgment here, this is the method supported by IE browser, for other browsers to judge

Request.open (' GET ', ' index.php?number= ' +document.getelementbyid (' keyword '). value,true);

Request.send ();

This is the state property listener.

Request.onreadystatechange=function () {

if (request.readystate===4) {//here to determine whether the load succeeded

if (Request. STATUS===200) {//

var data=josn.prase (Request.respontext);//This is the parsing of JSON, mainly because the PHP page in the form of JSON return, to parse

if (data.success) {//If parsing succeeds,

document.getElementById (' SearchResult '). innerhtml=data.msg;//returns the results of the server directly to this page, which is the implementation of non-refresh technical points, their own understanding. Parse successfully returns JSON to set a successful health;

}else{

document.getElementById (' SearchResult '). Innerhtml= "error occurred" +DATA.MSG;

}

else{

Alert ("Error occurred" +request.readystate);//Error return error code

}

}

}

}

/* Below is the POST method to hold */

document.getElementById ("Save"). onclick = function () {
var request = new XMLHttpRequest ();
Request.open ("Post", "index.php");//For POST do not pass value after the address bar,
var data = "Name=" + document.getElementById ("Staffname"). Value
+ "&number=" + document.getElementById ("Staffnumber"). Value
+ "&sex=" + document.getElementById ("Staffsex"). Value
+ "&job=" + document.getElementById ("Staffjob"). value;//to set data data with the same way as the Get method, note the Add & sign
Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");//Setting this content means that the content of the request body is encoded in UTF-8 encoding, Let the server know that there are entity variables in the parameters. If the background does not accept the data, it always returns false, because the entity variable of data cannot be recognized, this method must be added after open and before send.
Request.send (data), which is passed to the server as a parameter to the Send method.
Request.onreadystatechange = function () {//Listening state property
if (request.readystate===4) {//indicates that the interaction state is complete.

The 0:xmlhttprequest object has not yet completed initialization.
The 1:xmlhttprequest object begins sending the request.
The request to send the 2:xmlhttprequest object is complete.
The 3:xmlhttprequest object starts reading the server's response.
4:xmlhttprequest Object Read server response ended. Similar to the call process.


if (request.status===200) {indicates that XMLHTTP is in normal interaction with the background, or that it is interacting
var data = Json.parse (request.responsetext); there are two kinds of decoding methods in//json one is eval, One is json.parse, but Eval is unsafe, for some window.location= "address" in JSON, also directly to use, this will cause the website of the loophole.
if (data.success) {
document.getElementById ("Createresult"). InnerHTML = data.msg;
} else {
document.getElementById ("Createresult"). InnerHTML = "Error occurred:" + data.msg;
}
} else {
Alert ("Error occurred:" + request.status);
}
}
}
}

}

<body>
<label> Employee ID:</label>
<input type= "text" id= "keyword"/>
<button id= "Search" > Inquiries </button>
<p id= "SearchResult" ></p>

<label> Employee Name:</label>
<input type= "text" id= "Staffname"/><br/><br/>
<label> Employee Gender:</label>
<select id= "Staffsex" >
<option> Men </option>
<option> Women </option>
</select><br/><br/>
<label> Employee Age:</label>
<input type= "text" id= "Staffage"/><br/><br/>
<label> Employee ID:</label>
<input type= "text" id= "Staffnumber"/><br/><br/>
<button id= "Save" > Save </button>
<p id= "Createresult" ></p>

</body>

2. The following is the index.php page

Set page content is HTML encoded format is UTF-8
Header ("content-type:text/plain;charset=gb2312");
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 employees by Employee number
Function search () {
//check for an employee number parameter
//isset detect if the variable is set; empty value is no null
//Hyper global variable $_get and $_post Used to collect form data
if (!isset ($_get["number"]) | | empty ($_get["number"]) {
echo ' {"Success": false, "MSG": "Parameter Error"} ';
Return Variables declared outside of the
}
//function have Global scope and can only be accessed outside of the function.
//global keywords are used to access global variables within functions
Global $staff;
Gets the number parameter
$number = $_get["number"];
$result = ' {' success ': false, ' msg ': ' No employee found. "}‘;

//traverse the $staff multidimensional array to find out whether an employee with a key value of number exists and, if present, modify the return result
foreach ($staff as $value) {
if ($value ["number"] = = $ Number) {
$result = ' {' Success ': true, ' msg ': ' Find Employee: Employee ID: '. $value ["Number"].
', 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 ' {"Success": false, "MSG": "Parameter error, employee information not complete"} ";
Return
}
TODO: Get post form data and save to database

Prompt to save successfully
Echo ' {' success ': true, ' msg ': ' Employee: '. $_post["Name"]. ' Information saved successfully! "}‘;
}

About AJAX mates JSON array implementation no refresh

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.