JSON を使用して、クライアント/サーバー間のデータを管理したいと考えています。ただし、JSON 以外はすべて機能します... Python サーバーから来ていると思いますが、サーバープログラミングの専門家ではないため、Python サーバーで変更する方法が本当にわかりません。内部でプログラムする方法が本当にわからないので、私のpythonサーバーは本当にシンプルです。JSON を使用しない場合は完全に機能しますが、データを並べ替えるのはあまり効率的ではありません。jsonを受け入れるようにpythonサーバーを変更する簡単な方法はありますか(pythonサーバーからのものである場合)?
これが私のhtmlです:
<form method="post" id="formu" >
<textarea class="field span10" id="sequence" name="sequence" cols="4" rows="5"></textarea>
<input type="submit" value="Submit" class="btn btn-primary">
</form>
私のJavaScript:
$(document).ready(function() {
// formular
$('#formu').on('submit', function(e) {
e.preventDefault(); // Prevent default behavior
var sequence = $('#sequence').val();
$.ajax({
url : 'test.py',
type : 'post',
data : JSON.stringify({'sequence' : sequence}),
dataType: 'json',
success : function(data){
alert(data);
} // end of success function
}); // end of ajax
});
});
ajax (test.py) の私の python コード:
import json
result = {'myresult':'lalalalalal'};
myjson = json.load(sys.stdin)
result['fromclient'] = myjson['sequence']
print 'Content-Type: application/json\n\n'
print json.dumps(result)
そして私のpythonサーバー:
#!/usr/bin/python
import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable()
import mimetypes
mimetypes.add_type("image/svg+xml", ".svg", True)
mimetypes.add_type("image/svg+xml", ".svgz", True)
mimetypes.add_type("application/javascript", ".js", True)
mimetypes.add_type("text/javascript", ".js", True)
mimetypes.add_type("text/plain", ".txt", True)
mimetypes.add_type("text/html", ".html", True)
mimetypes.add_type("application/perl", ".pl", True)
mimetypes.add_type("application/json", ".json", True)
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("127.0.0.1", 8080)
#handler.cgi_directories = ['/FOLDOMEweb']
handler.cgi_directories = ['/WEBSERVER']
httpd = server(server_address, handler)
try:
print "Running HTTP server"
httpd.serve_forever()
except KeyboardInterrupt:
print "Server Stoped"