I'm trying to answer an ajax-request with a python script. The ajax-request sends a json-object just like follows:
$.ajax({
url : "cgi-bin/mycgi.py",
type : "POST",
data : JSON.stringify(MyJSONObject),
success : function() {...do something},
error : function(xhr,errmsg,err) {
alert(xhr.status);
}
}
My Python script mycgi.py has the following lines:
import sys
import simplejson as json
...
myjson = json.loads(sys.stdin.read())
#do something with the object
mystatus = "200 OK"
sys.stdout.write("Status: %s\n" % mystatus)
sys.stdout.write("Content-Type: application/json")
sys.stdout.write("\n\n")
sys.stdout.write(json.dumps(myjson))
Basically everything works fine. My browser gets the response, recognizes - if status is set to "200 OK" - that the request was successfull and runs the commands in the success-part with the returned object.
But I have two questions:
- How can I get my script to return errors with an error-Message? I can return "404" instead of "202 OK" and my browser realizes, that there is an error. But I have no good idea how to return an error-Message. Do I have to put this message in the header of my response?
- I would like to know, if my way of communication between client and server is "too simple" and perhaps too riskful. When i read other questions here with similar problems, I saw that people work with python-modules like "request" or derive a class from BaseHTTPRequestHandler. I would like to keep my python-scripts as simple as possible. Is it - out of some reason - perhaps necessary to go another way?
Thanks a lot!