2.$.getJSON():远程获取JSON

什么是JSON? JavaScript Object Notation,是一种轻量级的数据交换格式。

我们还是先看代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//	$.getJSON()
	var jsonUrl = "ajax/json.php";
	$("#getJSONForm").submit(function(){
		var q = $("#q").val();
		if (q.length == 0) {
			$("#q").focus();
		} else {
			$("#result").html(ajax_load);
			$.getJSON(
				jsonUrl,
				{q: q},
				function(json) {
					var result = "Language code is \"<strong>" + json.responseData.language + "\"";
					$("#result").html(result);
				}
			);
		}
		return false;
	});

我们直接看第9行。
1. $.getJSON不是DOM的方法,所以函数的书写是直接$.getJSON,而不是$(“#result”).getJSON。
2. $.getJSON有三个参数,地址,远程访问请求的地址;需要提交的数据数组;回调函数。
3. $.getJSON只能通过GET方法向远程提交数据,不支持POST方式。
4. $.getJSON对返还的结果以JSON格式对待。

$.getScript():远程调取Javascript

我们知道javascript是客户端程序,需要下载至客户端来执行。如果我们需要针对性的加载javascript脚本,这一函数是有用的。

1
2
3
4
5
6
7
8
//	$.getScript()
	var scriptUrl = "ajax/script.php";
	$("#getScript").click(function(){
		$("#result").html(ajax_load);
		$.getScript(scriptUrl, function(){
			$("#result").html("");
		});
	});

1. $.getScript只支持两个参数,地址和回调函数。如果需要传递参数至远程服务器,只能通过修改地址的方法。
2. Javascript并不需要一定得是.js后缀名的文件。这里的例子当中的远程地址是php文件,也就是说可以动态生成一段代码出来。

4. $.get(): 提出GET请求

$.get()函数是最为普遍的提出GET请求的办法。它支持xml, html, script, json, 以及jonsp。

1
2
3
4
5
6
7
8
9
10
11
12
//	$.get()
	$("#get").click(function(){
		$("#result").html(ajax_load);
		$.get(
			loadUrl,
			{language: "php", version: 5},
			function(responseText){
				$("#result").html(responseText);
			},
			"html"
		);
	});

$.get()接受四个参数,除了地址,数据,回调函数外,还有就是指定远程响应数据的格式。

5. $.post(): 提出POST请求

基本同上。

1
2
3
4
5
6
7
8
9
10
11
12
//	$.post()
	$("#post").click(function(){
		$("#result").html(ajax_load);
		$.post(
			loadUrl,
			{language: "php", version: 5},
			function(responseText){
				$("#result").html(responseText);
			},
			"html"
		);
	});

最后,也是最重要的,$.()

因为篇幅过长,这个需要另外写一次。

转载请注明文章来自糗世界博客

页面: 1 2

«上一篇 网络富豪排行榜(前26) | 关于statusNet发中文邀请或者通知邮件时题头会产生乱码问题(续) 下一篇»

Tags: , ,

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">