óCoffeeScript Cookbook

AJAX

问题

你想使用jQuery的AJAX调用

方法

$ ?= require 'jquery' # For Node.js compatibility

$(document).ready ->
	# Basic Examples
	$.get '/', (data) ->
		$('body').append "Successfully got the page."

	$.post '/',
		userName: 'John Doe'
		favoriteFlavor: 'Mint'
		(data) -> $('body').append "Successfully posted to the page."

	# Advanced Settings
	$.ajax '/',
		type: 'GET'
		dataType: 'html' error: (jqXHR, textStatus, errorThrown) ->
			$('body').append "AJAX Error: #{textStatus}"
		success: (data, textStatus, jqXHR) ->
			$('body').append "Successful AJAX call: #{data}"

jQuery 1.5 及更高的版本补充了一个新的API,用于处理不同的回调事件。

	request = $.get '/'
	request.success (data) -> $('body').append "Successfully got the page again."
	request.error (jqXHR, textStatus, errorThrown) -> $('body').append "AJAX Error: ${textStatus}."

详解

jQuery和 $ 这两个变量可以交换使用。参看 回调绑定