Topic:
1. Imitate jquery's $.get to send ajax request, the following data types are optional parameters, if there is json, the data will be parsed by json, if there is no json parameter, the data will not be parsed. The result after the call is as follows:
2. Use the same logic to complete the encapsulation of the post request. Note: the post request has the processing of request parameters
Analysis:
1. First, create an html document responsible for calling the function, and the js document encapsulates the function. Import related js package
file placement relationship is as follows:
html into the title and js to import the encapsulation function:
2. Because of the calling method of the above topic, it can be seen that the get and post mode requests can be regarded as the invocation of the object. So the first step is to create myajax as an object in the Myajax.js document, and put the function in it.
3. Encapsulate the get request function, the principle is to use xhr to initiate a get request.
4. Encapsulate the post request function, the principle is to use xhr to initiate a post request.
5. Call result
full source code
index.html:
<head>
<script src="Myajax.js"></script>
</head>
<body>
<script>
// get请求
myajax.get('https://这里输入自己的get地址', function(data) {
console.log(data);
});
// post请求
myajax.post('https://这里输入自己的post地址', {
content: '是当过IG地方',
source: '大师傅',
author: '时代'
}, function(data) {
console.log(data);
});
</script>
</body>
Myajax.js:
var myajax = {
get: function(url, datafn) {
// console.log(url);
// console.log(datafn);
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var result = JSON.parse(xhr.responseText);
return datafn(result);
}
}
},
post: function(url, dataC, datafn) {
// console.log(url);
// console.log(dataC);
// console.log(datafn);
var arr = [];
for (var k in dataC) {
var str = k + '=' + dataC[k];
arr.push(str);
}
arr = arr.join('&');
// console.log(arr);
var xhr = new XMLHttpRequest;
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(arr);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var result = JSON.parse(xhr.responseText);
return datafn(result);
}
}
}
}