Summary of native js call json method, js call json
Ajax Basics
Ajax: allows you to read server information without refreshing new data.
HTTP Request Method:
GET: used to obtain data, such as browsing a post.
Ajax. judgeXmlHttpRequest ('get', 'index. php', function (data) {alert (data); // This is the data returned by the server })
POST: used to upload data, such as user registration
Var dataJson = {name: 'ys ', age: 123} ajax. judgeXmlHttpRequest ('post', 'index. php', function (data) {alert (data); // This is the data returned by the server}, dataJson)
Difference between GET and POST:
GET: pass through the url (put in the url), will put the transmitted data on the url, name = Value & name = Value
Small get capacity, low security, and Cache
POST: do not pass through the URL
Large post capacity, generally up to 2 GB, relatively high security, no cache
Native Ajax Compilation
Ajax operation steps
Create an Ajax object
Non-IE6 browsers:
var oAjax=new XMLHttpRequest();
Internet Explorer 6:
var oAjax=new ActiveXObject("Microsoft.XMLHTTP");
Connect to the server
Ajax. open (method, file name, asynchronous transmission );
Cache blocking method:
Ajax.open('GET','a.txt?t='+new Date().getTime(),true);
Synchronization: In js, you must specify one thing.
Asynchronous: multiple tasks must be done together in js.
Ajax performs asynchronous transmission instead of synchronization.
Send request
Ajax.send();
Receive Return Value
Request status monitoring: onreadystatechange event: triggered when there is a communication between your Ajax and the server. It mainly uses the readyState attribute to determine whether the end is complete or whether the end is successful. The status attribute determines whether the end is complete or not.
ReadyState property: Request status
0 (not initialized) has not called the open Method
1 (load) The send () method has been called and the request is being sent.
2 (Load completed) send () method is completed, and all corresponding content has been received
3 (resolution) parse the received response content
4 (complete) after the response content is parsed, it can be called on the client (completion is not necessarily successful, and status is required to check whether the response is successful or failed)
Status attribute:
Request result: Successful (200) or failed (404): Ajax. status = 200
Returned value responseText:
The text returned from the server: Ajax. responseText (the returned value is a string and sometimes needs to be further processed in other formats)
OAjax. onreadystatechange = function () {// oAjax. readyState: indicates the step at which the browser and server are connected. if (oAjax. readyState = 4) {// read if (oAjax. status = 200) {// The read result is successful alert ('success: '+ oAjax. responseText );}}}
The native Ajax is encapsulated into a function for use. The native Ajax code is:
The GET method encapsulates the following functions:
Function ajax (url, fnSuccess, fnFaild) {// 1. Create an Ajax object. In js, an error is reported when an undefined variable is used. An undefined attribute is used. When XMLHttpRequest is not defined in IE6, an error is reported. Therefore, if (window. XMLHttpRequest) {var oAjax = new XMLHttpRequest (); // non-IE6} else {var oAjax = new ActiveXObject ("Microsoft. XMLHTTP "); // IE6} // 2. connect to the oAjax server. open ('get', url, true); // 3. send a request to oAjax. send (); // 4. receives the returned value oAjax. onreadystatechange = function () {// oAjax. readyState -- the path between the browser and the server if (oAjax. readyState = 4) {// read if (oAjax. status = 200) {// The read result is fnSuccess (oAjax. responseText); // The function executed when the request is successful} else {if (fnFaild) {// determines whether the input fails to be a function, that is, whether the user cares about the result fnFaild (oAjax. responseText); // handle the cause of the failure }}}}}
The function encapsulated by the POST method is:
Function ajaxPost (url, id, fnSuccess, fnFaild) {// 1. create an Ajax object if (window. XMLHttpRequest) {var xhr = new XMLHttpRequest (); // non-IE6} else {var xhr = new ActiveXObject ("Microsoft. XMLHTTP "); // IE6} // 2. connect to the server xhr. open ("POST", url, true); // sets the header information xhr. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); var form = document. getElementById (id); // 3. send request and pass data xhr. send (serialize (form); xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status >=200 & xhr. status <300) | xhr. status = 304) {fnSuccess (xhr. responseText);} else {fnFaild (xhr. responseText );}}};}
Character Set encoding: the encoding of the webpage and the requested file must be the same, for example, utf8
Cache, block cache (frequently changed data, etc., cannot be cached. It is mainly used for GET methods). When passing parameters, add? + 'Variable data' does not affect the original data.
ajax('a.txt?t='+new Date().getTime(),function(str){ alert(str);},function(str){ alert(str);});
Ajax request dynamic data: such as a json File
1. the ajax return value is a string that can be converted by eval to read the returned array/json data.
alert(str);alert(typeof(str));var arr=eval(str);alert(typeof(arr));alert(arr[1]);alert(arr[1].c);
2. Create elements in combination with DOM to display the returned content
OBtn. onclick = function () {ajax ('data/arr3.txt? T = '+ new Date (). getTime (), function (str) {var arr = eval (str); for (var I = 0; I <arr. length; I ++) {var oLi = document. createElement ('lil'); oLi. innerHTML = 'user name: <span> '+ arr [I]. user + '</span> password: <span>' + arr [I]. pass + '</span>'; oUl. appendChild (oLi) ;}, function (str) {alert (str );});}
Data Type --> the returned data type may be xml (almost obsolete), json (currently commonly used)
The following is an example of using the get method to call json in native js:
If (! IsNaN (matchId) {var xmlHttp = null; try {// Chrome, Firefox, Opera, Safari xmlHttp = new XMLHttpRequest ();} catch (e) {try {// Internet Explorer IE 6.0 + xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP");} catch (e) {try {// Internet Explorer IE 5.5 + xmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");} catch (e) {alert (" your browser not support ajax! ") ;}} Window. onload = function () {xmlHttp. open (" get ",/api/clientMatch/commonmatchdi.pdf. json? MatchId = "+ matchId, true); xmlHttp. send (); xmlHttp. onreadystatechange = doResult; // set the callback function}; function doResult () {var html = ''; if (xmlHttp. readyState = 4) & (xmlHttp. status = 200) {// 4 indicates that the execution is completed, and 200 indicates that the execution is successful. var data = JSON. parse (xmlHttp. responseText); if (data. code = 200) {// code execution} document. getElementById ('appmatch '). innerHTML = html ;}}}