Python 使用sys.exit()后将JSON返回到AJAX
我正在使用一个本地web应用程序,它通过AJAX在web服务器上执行Python脚本 我试图在远程服务器上部署该应用程序,此后一直面临AJAXPython 使用sys.exit()后将JSON返回到AJAX,python,json,ajax,cgi,Python,Json,Ajax,Cgi,我正在使用一个本地web应用程序,它通过AJAX在web服务器上执行Python脚本 我试图在远程服务器上部署该应用程序,此后一直面临AJAXstatusText:“parsererror” 我假设这是因为当脚本失败时,它没有收到预期的正确JSON如何确保脚本中断将JSON返回到浏览器,以便了解错误的性质? AJAX调用如下所示: $.ajax({ async: true, type: "POST", url: "cgi-bin/mysc
statusText:“parsererror”
我假设这是因为当脚本失败时,它没有收到预期的正确JSON如何确保脚本中断将JSON返回到浏览器,以便了解错误的性质?
AJAX调用如下所示:
$.ajax({
async: true,
type: "POST",
url: "cgi-bin/myscript.py",
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
data: JSON.stringify(run_details),
dataType: "JSON"
})
.done(function(data) {
console.log(data)
})
.fail(function(xhr) {
console.log('Error in myscript (cf. Ajax error below).');
console.log('error',xhr);
});
在工作条件下,我使用以下方法将数据返回到客户端,这种方法在本地服务器上运行良好:
success_message = "Some text"
result = {'message': success_message};
#Send JSON result back to Ajax
print("This line allows the following to be received by browser \n")
json.dump(result, sys.stdout)
如果脚本中出现错误,我调用此函数来中断脚本:
def interruptScript(a_cursor, a_conn, error_message):
# Close communication with the database
a_cursor.close()
a_conn.close()
#Add error message to object
result = {'message': error_message};
#Send JSON result back to Ajax
print("This lines allows the following to be received by browser \n")
json.dump(result, sys.stdout)
sys.exit(1)
理想情况下,我希望可以在AJAX的“responseText”(现在为空)中访问错误消息
到目前为止,我尝试在sys.exit()
中包含一个字符串(即sys.exit(error_message)
)和一个JSON字符串(即sys.exit(JSON.dumps(result))
),但在PyDev中调试时我了解到TypeError:integer是必需的(get type str)
,这可能是一个错误。因此,我最终添加了整数1
,希望json.dump
内容在sys.exit
之前通过AJAX传递
更新: 我找到了导致错误的原因(远程服务器的python安装中缺少python包)。不过,我将保留这个问题,因为原则上,我仍然有兴趣知道如何确保来自Python的错误消息(无论是来自我的自定义interruptScript()函数,还是直接来自Python的通知未安装包的错误消息)正确推送到浏览器。我使用的是cgib.enable(),所以问题主要是,如果AJAX需要JSON,如何推送错误消息?