Javascript uses json to implement simple ajax instances and jsjsonajax instances

Source: Internet
Author: User

Javascript uses json to implement simple ajax instances and jsjsonajax instances

Preparations

1. Install wampserver or other similar software to build a local integrated installation environment. I installed phpstudy.
2. html, js, css, and other files must be placed in the WWW directory of PHPstudy. The index page is run by default.
32.16bootstrap.css

Interface:

Phpstudyis easy to use. If you have not installed php on your computer, configure the system environment variable first, add php.exe (in the PHPstudy installation directory) to php.exe, enter php-v in cmd, and check the php installation version.

Create a project in the WWW folder of PHPstudy. Here I name it AjaxDemo.

Index.html

<! DOCTYPE html> 

StaffManage. js

Instantiation of Ajax can be divided into five points. It is easy to remember:

1. A new XMLHttpRequest instance
Be sure to be compatible with earlier ie browsers

var xhr; if (window.XMLHttpRequest) { xhr= new XMLHttpRequest(); } else { xhr= new ActiveXObject(‘Microsoft.XMLHTTP'); } 

2. open (method, url, asyn)
The open () method of the XMLHttpRequest object has three parameters. The first parameter specifies GET or POST, the second parameter specifies the URL address, and the third parameter specifies whether Asynchronous is used. The default value is true, therefore, you do not need to write.

3 * If a post request is added with the request header setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ")

4. send
The send () method is called to actually send the request. The GET request does not require parameters. the post request must pass the body part in a string or FormData object.

5. onReadyStateChange

6. responseText

// Query the employee method var oKeyword = document. getElementById ('keyword'), // employee ID oSearchBtn = document. getElementById ('search'), // query button oSearchRes = document. getElementById ('searchresult'); // The feedback result is displayed // query the employee button and click the event oSearchBtn. onclick = function () {searchStaff ();} // create the query employee method function searchStaff () {// var xhr = new XMLHttpRequest (); // The standard writing method and IE writing method are mixed, and can be compatible with earlier IE browsers var xhr; if (window. XMLHttpRequest) {xhr = new XMLHttpRequest ();} Else {xhr = new ActiveXObject ('Microsoft. xmlhttp');} xhr. open ('get', 'serverjson. php? Number = '+ oKeyword. value); xhr. send (); // when the XMLHttpRequest object is created, you must first set the onreadystatechange callback function. In the callback function, we usually only need to use readyState = 4 to determine whether the request has been completed. If the request has been completed, we can determine whether a successful response is based on status = 200. Xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200) {var data = JSON. parse (xhr. responseText); // json resolution method JSON. parse or eval ('+ xhr. responseText + ') oSearchRes. innerHTML = data. msg ;}}// add employee var oAddnumber = document. getElementById ('add-number'), // employee ID oAddname = document. getElementById ('add-name'), // employee name oAddsex = document. getElementById ('add-sex'), // employee gender oAddjob = document. GetElementById ('add-job'), // employee position oAddSearch = document. getElementById ('add-search'), // add employee button oAddResult = document. getElementById ('add-resultshow '); // The feedback result is displayed. // click the add employee button to click the event oAddSearch. onclick = function () {createStaff () ;}// create the Add employee method function createStaff () {var xhr; if (xhr. XMLHttpRequest) {xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject ('Microsoft. XMLHTTP ');} xhr. open ('post', 'serverjson. p Hp '); // note that no space is displayed on both sides of the equals sign of key = value, and the error var data = 'name =' + oAddname will appear. value + '& number =' + oAddnumber. value + '& sex =' + oAddsex. value + '& job =' + oAddjob. value; // set Content-Type xhr between open and send. setRequestHeader ('content-type', 'application/x-www-form-urlencoded'); xhr. send (data); xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200) {var data = JSON. parse (xhr. responseText); if (data. success) {OAddResult. innerHTML = data. msg;} else {oAddResult. innerHTML = 'error: '+ data. msg ;}} else {alert (' error! '+ Xhr. status )}}}}

Serverjson. php

<? Php // set the page Content to html encoding format to utf-8header ("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 multi-dimensional array, contains employee information. Each employee information is an array $ staff = array ("name" => "Hong Qi", "number" => "101 ", "sex" => "male "," Job "=>" General Manager "), array (" name "=>" Guo Jing "," number "=>" 102 "," sex "=>" male ", "job" => "Development Engineer"), array ("name" => "Huang Rong", "number" => "103", "sex" => "female ", "job" => "Product Manager"); // you can search for a get request. For a POST request, the newly created // $ _ SERVER is a super global variable and is available in all scopes of a script, you do not need to use the global keyword // $ _ SERVER ["REQUEST_METHOD"] to return the request method if ($ _ SERVER ["REQUEST_METHOD"] = "GET") used to access the page ") {search ();} elseif ($ _ SERVER ["REQUEST_METHOD"] = "POST") {create ();}// Search for employee function search () {// check whether there are employee ID parameters // isset check variables; whether the empty value is null or not. // The Super global variables $ _ GET and $ _ POST are used to collect form data if (! Isset ($ _ GET ["number"]) | empty ($ _ GET ["number"]) {echo '{"success": false, "msg ": "parameter error"} '; return;} // variables declared outside the function have a Global scope and can only be accessed outside the function. // The global keyword is used to access the global variable global $ staff in the function; // obtain the number parameter $ number = $ _ GET ["number"]; $ result = '{"success": false, "msg": "No employee found. "} '; // Traverse the $ staff multi-dimensional array to check whether the employee whose key value is number exists. If yes, modify the returned result foreach ($ staff as $ value) {if ($ value ["number"] = $ number) {$ result = '{"success": true, "msg": "locate EMPLOYEE: employee ID :'. $ value ["number"]. ', employee name :'. $ value ["name"]. ', employee gender :'. $ value ["sex"]. ', employee position :'. $ value ["job"]. '"}'; break;} echo $ result;} // create employee function create () {// determine whether the information is completely filled in 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. The employee information is incomplete."} '; return;} // TODO: Get the POST form data and save it to the database. // The system prompts that the data is saved successfully. echo' {"success ": true, "msg": "Employee :'. $ _ POST ["name"]. 'The information is saved successfully! "} ';}?>

Summary

The entire process is probably

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.