codecamp

CoffeeScript AJAX

AJAX

问题

你想要使用jQuery来调用AJAX。

解决方案

$ ?= require 'jquery' # 由于 Node.js 的兼容性

$(document).ready ->
    # 基本示例
    $.get '/', (data) ->
        $('body').append "Successfully got the page."

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

    # 高级设置
    $.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和$变量可以互换使用。另请参阅Callback bindings

CoffeeScript 扩展内置对象
CoffeeScript 回调绑定
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

CoffeeScript 数据库

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }