代码改变世界

Ajax请求

2019-09-02 19:28  錾子  阅读(107)  评论(0)    收藏  举报

Ajax

异步javaScript和XML
Ajax工作原理
 JavaScript 
 异步数据获取技术XMLHttpRequest
 xml
 Dom
 XHTML和css   

json

json是 JavaScript Object Notation 的首字母缩写,单词的意思是javascript对象表示法,这里说的json指的是类似于javascript对象的一种数据格式,目前这种数据格式比较流行,逐渐替换掉了传统的xml数据格式。
与json对象不同的是,json数据格式的属性名称和字符串值需要用双引号引起来,用单引号或者不用引号会导致读取数据错误。

ajax局部刷新和无刷新

$ajax使用方法

$.ajax使用方法 
常用参数:
1、url 请求地址
2、type 请求方式,默认是'GET',常用的还有'POST'
3、dataType 设置返回的数据格式,常用的是'json'格式,也可以设置为'html'
4、data 设置发送给服务器的数据
5、success 设置请求成功后的回调函数
6、error 设置请求失败后的回调函数
7、async 设置是否异步,默认值是'true',表示异步

Ajax写法

$.ajax({
    url: 'js/data.json',
    type: 'GET',
    dataType: 'json',
    data:{'aa':1}
    success:function(data){
        alert(data.name);
    },
    error:function(){
        alert('服务器超时,请重试!');
    }
});
====================================================================
$.ajax({
    url: 'js/data.json',
    type: 'GET',
    dataType: 'json',
    data:{'aa':1}
})
.done(function(data) {
    alert(data.name);
})
.fail(function() {
    alert('服务器超时,请重试!');
});


示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax请求</title>
</head>
<body>
    <p>姓名: <span id="username"></span></p>
    <P>年龄: <span id="userage"></span></P>
</body>
<script src="js/jquery-3.4.1.js"></script>
<script>
$.ajax({
    url:"data.json",
    type:"get",
    dataType:"json"
})
    .done(function (dat) {
        $("#username").html(dat.name);
        $('#userage').html(dat.age);
    })
    .error(function () {
        alert("服务器请求超时");
    })
</script>
</html>