Using AJAX / JSON
Dr. Charles Severance
[Link]
[Link]
[Link]
Browser Linux
[Link] Django
Click Routing [Link]
[Link]
Parse
D Views Templates
Response
O
M [Link]
Database
Shell
JavaScript Models
[Link]
/admin
[Link]
Browser Linux
[Link] Django
Routing [Link]
[Link]
Parse
D Views Templates
Response
O
M [Link]
Database
AJAX Shell
JavaScript Models
[Link]
/admin
[Link]
Data on the Web (2003)
• With the HTTP Request/Response well understood and well supported,
there was a natural move toward exchanging data between programs
using these protocols.
• We needed to come up with an agreed way to represent data going
between applications and across networks.
Agreeing on a “Wire Format”
PHP JavaScript
Array {
Object
"name" : "Chuck",
"phone" : "303-4456"
}
Python Java
Dictionary HashMap
a.k.a. “ Wire Protocol” - What we send on the “ wire”
JSON is a “Wire Format”
Serialize
{
JavaScript "name" : "Chuck", Python
"phone" : "303-4456"
Object }
Dictionary
De-Serialize
JavaScript Object Notation
• Douglas Crockford –
“Discovered” JSON
• Object literal notation in
JavaScript
[Link]
[Link]
Derived from
the JavaScript
“constant”
syntax
Similar to
Python
Dictionary
syntax
who = {
"name": "Chuck", String
"age": 29, Integer
"college" : true, Boolean
"offices" : [ "3350DMC", "3437NQ" ], List/Array
"skills" : {
"fortran": 10, Object
"C++" : 5,
"C": 10,
"python" : '7'
};
}
JSON Syntax
[Link]
<script type="text/javascript">
who = {
"name": "Chuck",
"age": 29,
"college": true,
"offices" : [ "3350DMC", "3437NQ" ],
"skills" : { "fortran": 10, "C": 10,
"C++": 5, "python" : 7 }
};
[Link](who);
</script>
[Link]
[Link]:
path('jsonfun', [Link], name='jsonfun'),
[Link]:
import time
from [Link] import JsonResponse
def jsonfun(request):
[Link](2)
stuff = {
'first': 'first thing',
'second': 'second thing'
}
return JsonResponse(stuff)
[Link]
[Link]
A Chat App Using JSON
[Link]
[Link]
[Link]:
path('', [Link].as_view(), name='talk'),
path('messages', [Link].as_view(), name='messages'),
url(r'^static/(?P<path>.*)$', serve,
{'document_root': [Link](BASE_DIR, 'static'), 'show_indexes': True},
name='static'
)
[Link]:
class Message([Link]) :
text = [Link]();
owner = [Link](settings.AUTH_USER_MODEL, on_delete=[Link])
created_at = [Link](auto_now_add=True)
updated_at = [Link](auto_now=True)
[Link]
[Link]:
class TalkMain(LoginRequiredMixin, View) :
def get(self, request):
return render(request, 'chat/[Link]')
def post(self, request) :
message = Message(text=[Link]['message'], owner=[Link])
[Link]()
return redirect(reverse('chat:talk'))
[Link]
<form method="post">
{% csrf_token %}
<input type="text" name="message" size="60"/>
<input type="submit" value="Post"/>
</p>
</form>
<div id="chatcontent">
<img src="{% url 'chat:static' '[Link]' %}" alt="Loading..."/>
</div>
[Link]
<script type="text/javascript">
async function updateMsg() {
[Link]('Requesting JSON');
fetch("{% url 'chat:messages' %}", {cache: "no-store"})
.then((response) => [Link]())
.then((rowz) => {
[Link]('JSON data', rowz);
[Link]('chatcontent').innerHTML = "";
for (var i = 0; i < [Link]; i++) {
arow = rowz[i];
[Link]('chatcontent').innerHTML +=
'<p>'+arow[0] + '<br/> '+arow[1]+"</p>\n";
}
setTimeout('updateMsg()', 4000);
})
.catch((error) => {
alert(error);
});
[
["Hello from the other window", "13 minutes ago"],
} ["Hello world", "14 minutes ago"]
]
[Link]
[Link]("DOMContentLoaded", function(){
setTimeout('updateMsg()', 2000);
});
</script>
{% endblock %}
[Link]
[Link]:
class TalkMessages(LoginRequiredMixin, View) :
def get(self, request):
messages = [Link]().order_by('-created_at')[:10]
results = []
for message in messages:
result = [[Link], naturaltime(message.created_at)]
[Link](result)
return JsonResponse(results, safe=False)
[
["Hello from the other window", "13 minutes ago"],
["Hello world", "14 minutes ago"]
]
[Link]
Summary
• JSON is very simple and powerful.
• It is well supported and performant in many languages.
• JavaScript and Python/Django have excellent support.
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Continue new Contributors and Translators here
Severance ([Link]) as part of
[Link] and made available under a
Creative Commons Attribution 4.0 License.
Please maintain this last slide in all copies of the
document to comply with the attribution
requirements of the license. If you make a
change, feel free to add your name and
organization to the list of contributors on this
page as you republish the materials.
Initial Development: Charles Severance,
University of Michigan School of Information
Insert new Contributors and Translators here
including names and dates
Additional Source Information
• Image of Douglas Crockford is Copyright Charles R. Severance and licensed as CC-BY