Created
December 2, 2015 14:21
-
-
Save nonZero/a17297cad1831ebc40d4 to your computer and use it in GitHub Desktop.
simple ajax examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% load staticfiles %} | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> | |
<title>Ex Man!!!!!</title> | |
<!-- Bootstrap --> | |
<link rel="stylesheet" | |
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"/> | |
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> | |
<!-- WARNING: Respond.js doesn't work if you view the page via file:// --> | |
<!--[if lt IE 9]> | |
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> | |
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> | |
<![endif]--> | |
</head> | |
<body> | |
<div class="container"> | |
<p> | |
<div class="pull-right"> | |
<span id="update-btn" | |
class="btn btn-default" | |
data-url="{% url "rate" %}" | |
>update!</span> | |
NIS = <span id="rate">{{ rate }}</span> USD | |
• | |
{% if user.is_authenticated %} | |
{{ user }} | |
<a class="btn btn-default" href="{% url "logout" %}">Logout</a> | |
{% else %} | |
<a class="btn btn-primary" href="{% url "login" %}">Login</a> | |
{% endif %} | |
</div> | |
<strong>Ex Man!</strong> | |
</p> | |
<hr/> | |
<h1> | |
{% block header %} | |
HEADER GOES HERE | |
{% endblock %} | |
</h1> | |
{% block content %} | |
CONTENT GOES HERE | |
{% endblock %} | |
<div id="cart"> | |
<span id="update-cart" | |
class="btn btn-default" | |
data-url="{% url "cart" %}" | |
>update cart!</span> | |
<ul id="items"></ul> | |
<p id="total"></p> | |
</div> | |
<input id="foo"/> | |
<span id="send" | |
class="btn btn-default" | |
data-url="{% url "chat" %}" | |
>Send chat message!</span> | |
</div> | |
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> | |
<script src="{% static "js/csrf.js" %}"></script> | |
<script src="{% static "js/rates.js" %}"></script> | |
</body> | |
</html> | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function () { | |
"use strict"; | |
function getCookie(name) { | |
var cookieValue = null; | |
if (document.cookie && document.cookie != '') { | |
var cookies = document.cookie.split(';'); | |
for (var i = 0; i < cookies.length; i++) { | |
var cookie = jQuery.trim(cookies[i]); | |
// Does this cookie string begin with the name we want? | |
if (cookie.substring(0, name.length + 1) == (name + '=')) { | |
cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); | |
break; | |
} | |
} | |
} | |
return cookieValue; | |
} | |
var csrftoken = getCookie('csrftoken'); | |
function csrfSafeMethod(method) { | |
// these HTTP methods do not require CSRF protection | |
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); | |
} | |
$.ajaxSetup({ | |
beforeSend: function (xhr, settings) { | |
if (!csrfSafeMethod(settings.type) && !this.crossDomain) { | |
xhr.setRequestHeader("X-CSRFToken", csrftoken); | |
} | |
} | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function () { | |
"use strict"; | |
$("#update-btn").click(function () { | |
var el = $(this); | |
if (el.attr("disabled")) { | |
return; | |
} | |
var url = el.data("url"); | |
el.attr('disabled', "true"); | |
$("#rate").load(url, function (respText, status, xhr) { | |
if (status == "error") { | |
$("#rate").css('background', 'red'); | |
} | |
el.removeAttr('disabled'); | |
}).text("?").css('background', ''); | |
console.log("clicked!"); | |
}); | |
$("#update-cart").click(function () { | |
var el = $(this); | |
if (el.attr("disabled")) { | |
return; | |
} | |
var url = el.data("url"); | |
el.attr('disabled', "true"); | |
$.get(url) | |
.success(function (data) { | |
$.each(data.items, function (i, item) { | |
$("<li>").text(item).appendTo($("#items")); | |
}); | |
$("#total").text(data.total); | |
}) | |
.error(function () { | |
alert("something went wrong"); | |
}); | |
console.log("clicked!"); | |
}); | |
$("#send").click(function () { | |
var el = $(this); | |
if (el.attr("disabled")) { | |
return; | |
} | |
var url = el.data("url"); | |
el.attr('disabled', "true"); | |
$.post(url, {text: $("#foo").val()}) | |
.success(function (data) { | |
alert("ok"); | |
}) | |
.error(function () { | |
alert("NOT OK"); | |
}); | |
console.log("clicked!"); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from authtools.views import LoginRequiredMixin | |
from django.core.urlresolvers import reverse_lazy | |
from django.http import HttpResponse | |
from django.http.response import JsonResponse | |
from django.utils import timezone | |
from django.views.generic import ListView, CreateView | |
from django.views.generic import View | |
from rest_framework import viewsets | |
from rest_framework.decorators import list_route | |
from rest_framework.response import Response | |
from exman.rates import get_current_rate | |
from expenses import serializers | |
from . import models | |
class HomeView(LoginRequiredMixin, ListView): | |
model = models.Expense | |
def get_queryset(self): | |
return super().get_queryset().filter(user=self.request.user) | |
def total(self): | |
qs = self.get_queryset() | |
return sum(x.amount for x in qs) | |
class AddView(LoginRequiredMixin, CreateView): | |
model = models.Expense | |
fields = ( | |
'timestamp', | |
'amount', | |
'details', | |
) | |
success_url = reverse_lazy("home") | |
def get_initial(self): | |
d = super().get_initial() | |
d['timestamp'] = timezone.now() | |
return d | |
def form_valid(self, form): | |
form.instance.user = self.request.user | |
return super().form_valid(form) | |
class RateView(View): | |
def get(self, request, *args, **kwargs): | |
time.sleep(3) | |
y = 1 / 0 | |
return HttpResponse(get_current_rate()) | |
class CartView(View): | |
def get(self, request, *args, **kwargs): | |
time.sleep(3) | |
cart = { | |
'items': [ | |
"milk", | |
"apples", | |
"potatoes", | |
"oranges", | |
], | |
'total': 35, | |
} | |
y = 1 / 0 | |
return JsonResponse(cart) | |
class ChatView(View): | |
def post(self, request, *args, **kwargs): | |
print(request.POST['text']) | |
return JsonResponse({'status': "OK"}) | |
class ExpenseViewSet(viewsets.ModelViewSet): | |
queryset = models.Expense.objects.all() | |
serializer_class = serializers.ExpenseSerializer | |
@list_route() | |
def total(self, request): | |
qs = self.get_queryset() | |
total = sum(x.amount for x in qs) | |
return Response({'total': total}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment