我想使用jQuery ajax和带有两个字段的简单Web窗体向python脚本发送值。我希望结果显示在同一个调用页面(index.html.en)的div标签内。使用jQuery返回同一页面的Python响应ajax
我有一个名为index.html.en的页面,我点击提交按钮,表单中的值被传递给python脚本(printname.py),结果被返回并显示在一个div标签中放在index.html.en页面的表单下。我花了最近两天寻找答案或例子,但我还没有找到答案或例子。我不确定自己正在尝试做什么,以及我想做什么的方式是可能的。我正在使用Mac OS Lion,并且我的网络服务器已启动并正在运行。目前我的代码验证字段不是空的,但它不返回任何内容。任何帮助,将不胜感激。我的代码和文件结构如下。
文件结构:
Library
WebServer
CGI-Exectutables/printname.py
Documents/projects/rambo/index.html.en
HTML文件:Index.html.en
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
function ValidateFields(){
$("#fname_error").hide();
$("#lname_error").hide();
var theForm = document.forms[0];
var isError = "false";
for (i=0;i<theForm.length;i++){
if(theForm.elements[i].getAttribute("type") == "text"){
var theFormField = theForm.elements[i];
var theFormFieldValue = theForm.elements[i].value;
if(theFormFieldValue == ""){
isError = "true";
var theFormFieldName = theForm.elements[i].getAttribute("name");
console.log(theFormFieldName);
switch (theFormFieldName)
{
case "first_name":
$("#fname_error").show();
break;
case "last_name":
$("#lname_error").show();
break;
}
}
}
}
if(isError == "true"){
return false;
}
//The reset method clears all fields on the form
theform.reset();
}
</script>
<script>
function Initialize_Form(){
$("#fname_error").hide();
$("#lname_error").hide();
}
</script>
<script>
$(document).ready(function() {
Initialize_Form();
$("#one").submit(function(){
ValidateFields();
event.preventDefault();
});
$.ajax(
{
type: "POST",
url: "/cgi-bin/printname.py",
data: "Catsup",
success: function(response)
{
$("#response_1").text("We returned python returned" + response);
}
});
return false;
});
</script>
<title>Mike's Test Ajax Python File</title>
</head>
<body>
<h1>Test Page</h1>
<form id="one" name="one">
<table>
<tr>
<td>first:</td>
<td><input type="text" name="first_name"></td>
<td><div id="fname_error"><p>first name is required</p></div></td>
</tr>
<tr>
<td>last:</td>
<td><input type="text" name="last_name"></td>
<td><div id="lname_error"><p>Last name is required</p></div></td>
</tr>
</table>
<input type="submit" value="submit">
</form>
<div id = "response_1"></div>
<div id = "response_2"></div>
</body>
</html>
的Python文件:printname.py
#!/usr/bin/python
import cgi, cgitb
form = cgi.FieldStorage()
fname = form.getvalue('first_name')
lname = form.getvalue('last_name')
print "Content-Type: text/html"
print
print (fname + ' ' + lname)
再说一遍,我是相当新的python和ajax,所以我不知道我是否试图做到这一点。
您的Javascript正在发送Ajax,但您的Python脚本期待CGI。看看这个链接,并确保你的服务器被配置为允许执行Python脚本:http://stackoverflow.com/questions/2201561/how-do-you-execute-a-server-side-python-script-using -jquery – paulsm4
是的,我的服务器被配置为允许执行Python脚本。提供的链接对我的问题没有帮助。 –