Skip to content

Instantly share code, notes, and snippets.

@duythinht
Created November 11, 2016 07:08
Show Gist options
  • Save duythinht/128f8c01cdc442b6d5a1097ca4dab23c to your computer and use it in GitHub Desktop.
Save duythinht/128f8c01cdc442b6d5a1097ca4dab23c to your computer and use it in GitHub Desktop.
What is jsonp?
from bottle import *
import json
@get('/users/:id')
def get(id):
# Check if request has callback query, return jsonp
if request.query.callback:
return request.query.callback + "(%s);" % json.dumps(user_by_id(id))
# else return json p
return user_by_id(id)
def user_by_id(id):
return {"id": id, "name": "User%s" %id}
# pip install bottle
# python app.py
# server run at localhost:3200
run(port=3200)
<!--
python -m SimpleHTTPServer
=> server run at localhost:8000
GOTO: http://localhost:8000/index.html
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
// This will be error
$.get('http://localhost:3200/users/1').then(user => alert(user.name)).catch(err => alert("Can't get via cross domain"));
// It's ok, trick more with DOM create script tag and append to head, stackoverflow for more infomation
function show(user) {
alert('got a user via jsonp');
alert(user.name)
}
</script>
</head>
<body>
<script src="http://localhost:3200/users/1?callback=show"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment