之前已经的博客有了一种简单实现ajax的方法,这里再补充另一种ajax的实现方法。
与之前不同的是,这里采用纯JavaScript的方法来实现ajax的get和post两种方法。
具体实现如下:
get
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
//you can do anything you want to edit your data
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var data = JSON.parse(xmlhttp.responseText);
var temp = "<h2>All Titles<h2>";
for(var i = 0;i<data.length;i++){
temp += `<p>Title:${data[i].title}</p>`;
}
$("#test").append(temp);
}
}
xmlhttp.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
xmlhttp.send();
post
$("#test1").on('click', function(){
var data =
{
"userId": $("#name").val(),
"id": $("#password").val(),
"title": "123",
"body": "12"
};
var param = "asdfadfasdga";
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("success!");
}
}
xmlhttp.open("post", "https://httpbin.org/post", true);
xmlhttp.send(JSON.stringify(data));//json is ok
//xmlhttp.send(JSON.stringify(param));//string is ok
});