Reputation: 131
I would like to use JSON to manage data between client/server. However, everything works except JSON... I think it come from my python server, but I am not specialist in server programming so I really don't know how to change in my python server. My python server is really simple because I really don't know how to program inside. If I don't use JSON it works perfectly but it is not really efficient to get sort the data. Is there a easy way to modify my python server to accept json (if it comes from python server)?
Here is my 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>
my 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
});
});
My python code for ajax (test.py):
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)
And my python server:
#!/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"
Upvotes: 0
Views: 441
Reputation: 3297
Don't use
data : JSON.stringify({'sequence' : sequence})
and pass the object to the jQuery ajax call. It'll handle the formatting itself. Remember form values are comprised of name, value pairs - so let jQuery do that for you.
Upvotes: 1