Skip to main content
 首页 » 编程设计

jquery之Parseerror 使用 ajax 将数据推送到 python 脚本

2025年05月04日37luoye11

我正在尝试使用 Ajax 将数据发送到 python 脚本,但我不断收到“parsererror”和返回 python 脚本的 responseText。

我已经尝试了各种组合,例如 {"data": "data"}、{data: "data"}、{data: data} 等,但没有任何效果。

也许你能看出问题

Ajax

var data = { 
    id: '20', 
    action: 'Test' 
}; 
$.ajax({ 
    type: "POST", 
    url: "./cgi-bin/datahandler.py", 
    data: data, 
    success: function (response) { 
        console.log(response); 
    }, 
    error: function(response) { 
        console.log(response); 
    }, 
}); 

python

#!c:/Python27/python.exe -u 
import cgi, cgitb 
 
cgitb.enable() 
 
data = cgi.FieldStorage() 
print "Content-Type: text/html\n" 
print "The id data is: " + data["id"].value 
print "<br />" 
print "The action data is: " + data["action"].value 
print "<br />" 
print data  

Apache

ScriptAlias /cgi-bin/ "c:/wamp/www/cgi-bin/" 
AddHandler cgi-script .py 
 
<Directory "c:/wamp/www/cgi-bin/"> 
    AllowOverride None 
    Options ExecCGI 
    Order allow,deny 
    Allow from all 
</Directory> 

响应文本

"#!c:/Python27/python.exe -u import cgi, cgitb cgitb.enable() data = cgi.FieldStorage() print "Content-Type: text/html\n" print "The id data is: " + data["id"].value print "<br />" print "The action data is: " + data["action"].value print "<br />" print data" 

请您参考如下方法:

根据您的评论,问题似乎与您的网络服务器中的 CGI 配置有关,即将您的 python 文件作为静态文件而不是 CGI 进行管理。

查看本教程:http://www.tutorialspoint.com/python/python_cgi_programming.htm

您需要将此行添加到您的 python CGI 文件(或您的 Win 系统中的等效行):

#!c:/Python30/python.exe -u 

apache 中的 CGI 配置可能是这样的:

LoadModule cgi_module modules/mod_cgi.so 
 
ScriptAlias /cgi-bin/ "c:/wamp/www/cgi-bin/" 
<Directory "c:/wamp/www/cgi-bin/"> 
   AllowOverride None 
   Order allow,deny 
   Allow from all 
   Options +ExecCGI 
   AddHandler cgi-script .py 
</Directory> 

请确保在配置目录之前加载 module_cgi。