$.ajax( )、$.getJson( )及JSON格式转换

通过cdn或本地引入jQuery:

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>

1、$.ajax( )

$(function(){
    $('#send').click(function(){
         $.ajax({
             type: "GET",
             url: "test.json",
             data: {username:$("#username").val(), content:$("#content").val()},
             dataType: "json",
             success: function(data){
                         $('#resText').empty();   //清空resText里面的所有内容
                         var html = ''; 
                         $.each(data, function(commentIndex, comment){
                               html += '<div class="comment"><h6>' + comment['username']
                                         + ':</h6><p class="para"' + comment['content']
                                         + '</p></div>';
                         });
                         $('#resText').html(html);
                      }
         });
    });
});

常用参数:
type: “GET | POST” ————- 数据请求方式,默认get
url:“” ————- 数据请求的地址
data: “” ————– 发送到服务器的数据,type为GET时为“ ”或不写data参数
dataType:”” ————– 从服务器返回的数据类型,有 “json | text | script | xml | html | jsonp ”
timeout:”” ————— 设置请求超时时间(毫秒)
async:”” ————— 是否异步请求,默认true
cache:”” ————— 从浏览器缓存中加载请求数据
success: function(data){…} ————— 成功后的回调函数
error: function(json){…} ————— 失败时的调用函数

简写:

$(function(){
    $.ajax({

        url:"http://***";

        success:function(data){
            //data 处理
        }

    });
});

2、$.getJSON( )

$(function(){

    $.getJSON('http://***',function(data){
        //data 处理
    });

});

3、JSON格式转换
对象转字符串: JSON.stringify( data );
字符串转对象: JSON.parse( data );

注意:json中只支持双引号,不支持单引号。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值