9
Ajax
Calvin Xiao edited this page 2014-01-26 19:42:36 -08:00
This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

##Pure Ajax

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

http://api.jquery.com/jQuery.ajax/ ,参见最后的Examples部分

最简单的例子是:

$.ajax("/user/1")
.done(function( html ) {
    $( "#results" ).append( html );
});

复杂一点的例子

$.ajax({
url: "/user/1",
cache: false
})
.done(function( html ) {
    $( "#results" ).append( html );
}).fail( function(jqXHR, textStatus){
   $('#results').html('Status: '+jqXHR.status+', Content: ' + jqXHR.statusText );
});

值得注意的几个参数是:

  • dataType: 可选html,xml,text,json,jsonp,也会根据返回的MIME type自行判断。
  • cache:为false时会自动在url后加上一个timestamp,设定了datatype是jsonp或script时默认为false,平时默认为true。
  • done 和 fail 两个函数的参数顺序不对称: jqXHR.done(function( data, textStatus, jqXHR ) {}); vs jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

##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);
}

又或者让Spring MVC自行转换JSONPObject

	@RequestMapping(value = "/web/mashup2", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public JSONPObject mashup2(@RequestParam(DEFAULT_JQUERY_JSONP_CALLBACK_PARM_NAME) String callbackName) {
		Map<String, String> map = Collections.singletonMap("content", "<p>你好,世界!</p>");
		return new JSONPObject(callbackName, map);
	}

mashup-client.jsp 是客户端

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