Ajax to Server (JSON) Communication
The word Ajax does not mean anything, it is just a term used to refer to a series of technologies that facilitate communication between client and server. Server communication is the core content of Ajax technology. Its goal is to send information from the client to the server and accept the return from the latter, in order to create a better user experience in the process. All server communication before Ajax was done on the server, so if you wanted to redraw part of the page, you either used an iframe (obsolete) or refreshed the entire page. Neither approach can be called a good user experience.
Ajax provides two types of server communication methods: synchronous communication and asynchronous communication.
Asynchronous communication Ajax is much more common than synchronous communication, with about 98% usage frequency. Asynchronous means that such Ajax calls are not triggered at the same time as other tasks. This communication behavior occurs in the background, is quite independent, and is separated from the page and web application.
Using asynchronous calls can avoid the blocking nature of synchronous calls, and it does not need to be processed together with other HTTP requests in the page.
XMLHttpRequest Object
The XMLHttpRequest object is the core of all Ajax calls. Our purpose is to use Ajax technology to asynchronously obtain the data in JSON and display it in an appropriate form:
//创建ajax通信服务器对象 function getHTTPObject(){ "use strict"; //注意使用严格模式 var xhr; //使用主流的XMLHttpRequest通信服务器对象 if(window.XMLHttpRequest){ xhr = new window.XMLHttpRequest(); //如果是老版本ie,则只支持Active对象 } else if(window.ActiveXObject){ xhr = new window.ActiveXObject("Msxml2.XMLHTTP"); } //将通信服务器对象返回 return xhr; }
Cross-browser compatibility issues: Microsoft Ie originally invented the XMLHttp object, which resulted in IE5 and IE6 only support ActiveXObject objects, so compatibility issues with them must be considered.
Create Ajax call
First, I created the Salad.json file in the local data directory and waited for the Ajax program to call it:
//ajax JSON Salad var ingredient = { "fruit":[ { "name" : "apple", "color" : "green" }, { "name" : "tomato", "color" : "red" }, { "name" : "peach", "color" : "pink" }, { "name" : "pitaya", "color" : "white" }, { "name" : "lettuce", "color" : "green" } ] };
Then what I have to do is send a request to the server and accept the transfer Returned data:
After receiving the returned server communication object "xhr", what we need to do next is to use the readystatechange event to perform the Ajax request status and server status on the communication object "xhr". When the readystate status request is completed and status When the status server is normal, it will carry out subsequent communication work.
//输出ajax调用所返回的json数据 var request = getHTTPObject(); request.onreadystatechange = function(){ "use strict"; //当readyState全等于“4”状态,status全等于“200”状态 代表服务器状态服务及客户端请求正常,得以返回 if(request.readyState ===4 || request.status ===200 ){ //为了方便起见,将数据打印到浏览器控制台(F12查看) console.log(request.responseText); } //使用GET方式请求.json数据文件,并且不向服务器发送任何信息 request.open("GET","data/ingredient.json",true); request.send(null); };
Ajax is also called through the GET and POST methods. The GET method exposes the data in the URL, so it requires less processing work; POST is relatively safe, but its performance is not as good as GET. Next, use the open() and send() methods to request data files and send data to the server respectively.
Usually in actual development projects, it is impossible to have just one Ajax call. For reuse and convenience, we need to encapsulate this Ajax program into a reusable function. Here I pass in an outputElement parameter to prompt the user to wait; I also pass in a callback parameter to pass in a The callback function matches the keywords typed by the user in the search box in the JSON file and renders the appropriate data to the page response location:
//将其封装成一个供调用函数 function ajaxCall(dataUrl,outputElement,callback){ "use strict"; //这是一段截取的js(ajax)代码 var request = getHTTPObject(); //我想要提醒大家的是:当网页的某个区域在向服务器发送http请求的过程中,要有一个标识提醒用户正在加载... outputElement.innerHTML = "Loding..."; //也可以根据各位的需求添加一个循环小动画 request.onreadystatechange = function () { if(request.readyState ===4 || request.status ===200){ //将request.responseText返回的数据转化成JSON格式 var contacts = JSON.parse(request.responseText); //如果回调函数是function类型,则使用callback函数处理返回的JSON数据 if(callback === "function"){ callback(contacts); } } }; request.open("GET","data/ingredient.json",true); request.send(null); }
Then calls ajaxCall():
//调用程序,我们将使用Ajax请求的JSON数据显示到HTML文档的某个区域中! (function () { "use strict"; //下面将给出DOM语句相对应的HTML代码 var searchForm = document.getElementById("search-form"), searchField = document.getElementById("q"), getAllButton = document.getElementById("get-all"), target = document.getElementById("output"); var search = { salad : function(event){ var output = document.getElementById("output"); //请求的JSON数据文件名,输出到HTML的区域,检索数据文件的核心function语句 ajaxCall('data/ingredient.json','output',function(data){ //searchValue为搜索条目,准备循环检索 var searchValue = searchField.value, //找到食材条目(详见JSON数据文件) fruit = data.fruit, //统计水果的数量 count = fruit.length, i; //阻止默认行为 event.preventDefault(); //初始化 target.innerHTML = ""; if(count > 0 || searchValue !==""){ for(i = 0;i < count;i++){ var obj = fruit[i], //将name与searchvalue值相匹配,如果值不等于 -1,那么就确定两者相匹配 inItfount = obj.name.indexOf(searchValue); //将JSON中匹配的数据规范的写入到DOM if(isItfount != -1){ target.innerHTML += '<p>'+obj.name+'<a href="mailto:" '+obj.color+'>'+obj.color+'</a></p>' } } } }) } }; //事件监听器,监听鼠标单击事件后调用函数并请求JSON数据文件 searchField.addEventListener("click",search.salad,false); })();
HTML document corresponding to Ajax:
<h1>制作沙拉所需要的食材</h1> <form action="" method="get" id="search-form"> <div class="section"> <label for="q">搜索食材</label> <input id="q" name="q" required placeholder="type a name"> </div> <div class="button-group"> <button type="submit" id="btn-search">搜索</button> <button type="button" id="get-all">get all contacts</button> </div> </form> <div id="output"></div>