POST数据到python脚本

时间:2013-12-17 07:25:29

标签: javascript jquery python html ajax

我有一个在我的本地服务器上托管的html页面,apache2,我想将一些数据发送到python脚本并对其进行操作,我使用的是当我使用表单的 action 标记时,它不会导航到下一页,当我尝试Jquery时,脚本不会被执行。有帮助吗?提前谢谢。

HTML:

<body>
  <div id="Header"></div>
    <div id="wrapper">
    <form name="login-form" class="login-form" action="/cgi-bin/test.py" method="post" onsubmit="validate();return false;">
      <div class="header">
        <h1>Enter Your Credentials</h1>
        <span>URL,Admin,Tenant,Password</span>
      </div>
      <div class="content">
        <input id="Uname" name="url" type="text" class="input username" placeholder="Keystone URL" />
        <div class="user-icon"></div>
        <input id="Pname"name="admin" type="password" class="input password" placeholder="Admin" />
        <div class="pass-icon"></div>
        <input id="oPass"name="password" type="password" class="input password" placeholder="Password" />
        <div class="pass-icon"></div>
        <input id="tenant"name="tenant" type="password" class="input password" placeholder="Tenant" />
        <div class="pass-icon"></div>   
      </div>
      <div class="footer">
        <input type="submit" name="submit" value="Submit" class="button"/>
      </div>
    </form>
  </div>
</body>

通过这种方式,脚本可以完美地执行,但不会导航到下一页。

Javascript功能:

function validate() {
    var un = document.getElementById("Uname").value;
    var valid = false;

    var unArray = ["http://192.168.1.102:5000/v2.0"]; 
    for (var i = 0; i < unArray.length; i++) {
        if ((un == unArray[i])) {
            valid = true;
            break; 
        }
    }

    if (valid) {
        alert("Login was successful"); 
        location.href = 'HomePage.html';
        document.login-form.action='/cgi-bin/test.py';

        return false; 
    } else {
        alert("Login was Unsuccessful");
        return false;
    }
}

这是我尝试的Ajax调用:

$.ajax({
  type: "POST",
  url: "/cgi-bin/test.py",
  data: "stuff_for_python="+document.getElementById("Uname").value,
  success: function(response) {    
      alert(response);      
  },
  error: function(data) {
      alert(data.responseText);
  }
});

Python脚本:

#!/usr/bin/python
import cgi, cgitb 
from StringIO import StringIO
import json
from io import BytesIO
import pycurl

cgitb.enable()
# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
url = form.getvalue('stuff_for_python')

print "Content-type: text/html\r\n\r\n\n"
print

print url
f = open('/home/stack/writing.txt','wb')
f.write(url)
f.close()

1 个答案:

答案 0 :(得分:1)

问题在于邮寄的数据值 试试这个:

$.ajax(
{
   type: "POST",
   url: "/cgi-bin/test.py" ,
   data: {stuff_for_python: document.getElementById("Uname").value},
   success: function(response)
   {
       alert(response);
   },
   error: function(data)
   {
       alert(data.responseText);
   },
});