Skip to content

Instantly share code, notes, and snippets.

@arkenous
Created April 30, 2016 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arkenous/d9d0944e7c1283f5011acdb6b7500482 to your computer and use it in GitHub Desktop.
Save arkenous/d9d0944e7c1283f5011acdb6b7500482 to your computer and use it in GitHub Desktop.
Ajax PythonCGI communicate sample using JSON format message
<!DOCTYPE html>
<html lang=ja>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AjaxPythonCGI</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-12">
<h1 class="text-center">Click below button to send sample text</h1>
<button type="button" class="btn btn-default btn-lg pull-right" id="button">Send</button>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12">
<textarea class="form-control" rows="2" placeholder="Received text is show here" id="result" disabled></textarea>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="js/sample.js"></script>
</body>
</html>
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import json
print("Content-type: application/json")
print("\n\n")
data = sys.stdin.read()
params = json.loads(data)
text = params['text']
result = {'text': text}
print(json.JSONEncoder().encode(result))
print('\n')
$(window).load(init());
function init() {
console.log("init");
$("#button").click(function() {
console.log("clicked");
var text = "Sample text";
send(text);
});
}
function send(text) {
console.log(text);
var json = JSON.stringify({'text': text});
$.ajax({
type: 'POST',
url: 'cgi/sample.cgi',
contentType: 'application/json',
data: json,
success: function(data) {
console.log(data);
console.log(data.text);
$('#result').empty();
$('#result').val(data.text);
}
});
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment