今天看了下jQquery中的getJSON()方法,做点小结:
原型:
jQuery.getJSON( url [, data ] [, success(data, textStatus, jqXHR) ] )
This is a shorthand Ajax function, which is equivalent to
官网解释:意思是$.getJSON是Ajax方法的简写,等价于下面的写法:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
由于我刚学jQuery,所以下面的写法也不甚理解。没关系,这不影响我照葫芦画瓢。
上面可以看出,url和seccess function是必须的,[data]是可选的,刚入门,就来个简单的。
首先新建一个ajax.php文件
<html> <head> <!-- 引入jQuery --> <script src="jquery-1.10.1.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $("#sent").click(function() { $.getJSON('ajax_json.php', function(data){ $.each(data, function(key, value) { $("#get_content").append(key + ':' + value + '<br/>'); }) }); }); }); </script> </head> <body> <button id="sent">Ajax</button> <div id="get_content"></div> </body> </html>
上面的文件是获取 ajax_json.php 文件中的json数据, ajax_json.php很简单,主要是json数据(这里顺便学习了json_encoe()函数)如下:
<?php $arr = array('name' => 'hui314', 'sex' => 'man'); echo json_encode($arr);
当点击id=“sent”这个button,id=“get_content”的div就会显示得到的json数据:
name:chen
sex:man
很简单:)