Skip to content
springside edited this page Mar 23, 2012 · 9 revisions

##Ajax

每一个Javascript框架都有对Ajax请求的简化, JQuery的API如下:

http://api.jquery.com/jQuery.ajax/

最简单的例子是:

$.ajax({
  url: "test.html",
  success: function(html){
    $("#results").append(html);
  }
});

值得注意的几个参数是:

  • dataType: 可选html,xml,text,json,jsonp
  • cache,为false时会自动在url后加上一个timestamp, datetype是jsonp或script时默认为false,平时默认为true

JQuery针对JSON格式的返回值的ajax请求还专门提供了一种$.getJson(url)函数,但统一起见还是建议用$.ajax().

##Cross Domain JSONP 这是个折腾人的事情,比如你现在的域名是abc.com,在上面的网页,浏览器是不允许你发ajax访问def.com的内容的。
但现在流行跨网站的mashup啊,最后搞出一种jsonp的模式,如果def.com真的打算让任意网站来访问自己的内容,就开放一个jsonp的接口出来。

IBM的这篇文章很好的解释了其中折腾的过程。 http://www.ibm.com/developerworks/cn/web/wa-aj-jsonp1/

在showcase中,有专门的Demo:

MashupServerController是输出JSONP格式数据的服务端,用了Jackson JSON提供的函数。

public String execute(@RequestParam("callback") String callbackName) {
	Map<String, String> map = Collections.singletonMap("content", "<p>Hello World!</p>");

	return mapper.toJsonP(callbackName, map);
}

mashup-client.jsp 是客户端

function fetchMashupContent() {
	$.ajax({
		url:remoteUrl, 
		dataType:"jsonp",
		success:function(data) {
			$('#mashupContent').html(data.content);
			$('#mashupContent').show();
	}});
}
Clone this wiki locally