javascript 从服务器请求数据(fetch,XHR和jQuery Ajax)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 从服务器请求数据(fetch,XHR和jQuery Ajax)相关的知识,希望对你有一定的参考价值。

/* *************** */
/* Using fetch API */
/* *************** */

fetch('https://jsonplaceholder.typicode.com/comments/3') 
	.then(function(response){ // server response as a stream
  	return response.json(); // parse text using fetch json() method
  })
  .then(function(myObj){ // parsed object passed as argument so something can done with data
  	console.log("Fetch:", myObj.email); // do something with data
  });

/* *************************** */
/* XmlHttpRequest (XHR) method */
/* *************************** */
  
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if(xhr.readyState == 4 && xhr.status == 200) {
    let myObj = JSON.parse(xhr.responseText); // get the response data as a string but immediately parse into an object
    console.log("XHR:", myObj.email);
  }
};
xhr.open('GET', 'https://jsonplaceholder.typicode.com/comments/3');
xhr.send();

/* *********** */
/* jQuery Ajax */
/* *********** */

$.ajax({
  method: 'GET',
  url: 'https://jsonplaceholder.typicode.com/comments/3',
  cache: false // do not cache the result
}).done(function(myObj){ // response data from request
  console.log("Ajax:", myObj.email); // so something with the data
});

以上是关于javascript 从服务器请求数据(fetch,XHR和jQuery Ajax)的主要内容,如果未能解决你的问题,请参考以下文章