1.原生的ajax
window.onload = function(){
// 1.创建XMLHttpRequest 判断语句是为了兼容更多的浏览器
var xmlhttp = {};
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest() //ie7以后的版本
}else{
xmlhttp = new ActiveXObiect("Microsoft.XMLHTTP") //ie7以前的版本
}
console.log("第一步的状态" + xmlhttp.readyState)
// 2.设置请求 发送请求的方法(open / send)
// open 方法: 语法:(请求类型,请求地址,异步/同步)
// 请求类型:GET 或 POST
// 请求地址:文件在服务器上的位置
// 异步/同步: 对应的值是 true / false 、不写的话默认是true(异步)
// send 方法: send(string) string:仅用于 POST 请求
xmlhttp.open('get','https://bird.ioliu.cn/joke/rand?type=text',true) //get、异步请求
console.log("第二步的状态" + xmlhttp.readyState)
// 3.发送请求
xmlhttp.send();
console.log("第三步的状态" + xmlhttp.readyState)
// 4.回调函数
xmlhttp.onreadystatechange = function(){
console.log("第四步的状态" + xmlhttp.readyState)
if(xmlhttp.readyState == 4 && xmlhttp.status ==200){
console.log(xmlhttp.responseText)
}else{
console.log("!!!!仔细检查代码!!!!")
}
}
}
2.使用jquery写的一个ajax
$(function(){
$("#btn").click(function(){
$.ajax({
url:"https://bird.ioliu.cn/joke/rand?type=text", //请求地址
type:"get", //请求方式
dataType:"json", //返回数据类型 xml、html、script、json、jsonp、text
// data:{ } 请求参数
success:function(value){ //成功后的回调函数
console.log(value);
console.log("数据请求成功");
$('#app').html(value)
},
error:function(){ //失败后的回调函数
console.log("数据请求失败")
}
})
})
})
3.关于解决跨域的问题 jsonp
需要先使用script标签把需要的数据链接引入
html代码:
<script src="http://cdn.weather.hao.360.cn/api_weather_info.php?app=hao360&_jsonp=weather&code=101010100"></script>
js代码:
function weather(value) {
console.log(value)
}
4.使用jquery写出 jsonp 解决跨域问题
$(function(){
$.ajax({
type:"post", //请求方式
async: true, //异步?同步?
url:"http://cdn.weather.hao.360.cn/api_weather_info.php?app=hao360&code=101010100", //请求的数据地址
dataType:"jsonp",
jsonp:"_jsonp",
jsonpCallback:"wang",
success:function(json){
console.log(json)
},
error:function(){
console.log("请求数据错误")
}
})
})