032-jQuery Ajax的getJSON和getScript方法

1. $.getJSON()方法

1.1. 通过HTTP GET请求载入JSON数据。

1.2. 语法

$.getJSON(url,data,function(response,textStatus,jqXHR))

1.3. 参数

1.4. 该函数是简写的Ajax函数, 等价于:

$.ajax({
	url: url,
	data: data,
	success: function(response,textStatus,jqXHR){},
	dataType: json
});

2. getScript()方法

2.1. getScript()方法通过HTTP GET请求载入并执行JavaScript文件。

2.2. 语法

$.getScript(url, function(response,textStatus,jqXHR))

2.3. 参数

2.4. 该函数是简写的Ajax函数, 等价于:

$.ajax({
	url: url,
	dataType: "script",
	success: function(response,textStatus,jqXHR){}
});

3. 例子

3.1. 新建一个名叫jQueryGetJSONScript的动态WEB工程

3.2. 新建index.html

<!DOCTYPE html>
<html>
	<head>
		<title>jQuery-Ajax的getJSON()和getScript()方法</title>
		<meta charset="utf-8" />

		<script type="text/javascript" src="jquery.js"></script>
		<script type="text/javascript">
			$(document).ready(function(){
				$('#btn1').click(function(){
					$.getJSON(
						'test.json',
						'r='+Math.random()+'&time='+new Date().getTime(),
						function(response,textStatus,jqXHR){
							$("#result").text('code='+response.data.code+', info='+response.data.info+', msg='+response.data.msg);
						}
					);
				});
				$('#btn2').click(function(){
					$.getScript(
						'test.js',
						function(response,textStatus,jqXHR){
							$(this).html(response);
						}
					);
				});
			});
		</script>
		<style type="text/css">
			div {
				width: 450px;
				height: 100px;
				background-color: pink;
			}
		</style>
	</head>
	<body> 
  		<div id="result">结果区域</div><br />
  		<button id="btn1">getJSON</button> <button id="btn2">getScript</button>
	</body>
</html>

3.3. 新建test.json

{"data": {"code": 1, "info": "success", "msg": "请求成功。"}}

3.4. 新建test.js

document.getElementById('result').innerHTML='我是服务器使用js返回的文本。';

3.5. 运行项目

猜你喜欢

转载自blog.csdn.net/aihiao/article/details/112397244