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

来源:互联网 发布:炉石淘宝买友谊赛值吗 编辑:程序博客网 时间:2024/06/07 05:18

通过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