通过Ajax发送到Python的URL位置

0 投票
2 回答
1629 浏览
提问于 2025-04-18 04:18

我正在尝试把一些代码拼凑在一起。我有两个不同的功能想要合并成一个。

代码是:

<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>

<body>
<center>

# first function
<form id="search_box"><input id="search_text" type="text"/></form>
<br/>

<div id="jQuery_send"></div>
<div id="python_response"></div>

<script>
  $('#search_box').submit(function() {
  $('#jQuery_send').text("jQuery sent: " + $('#search_text').val() );

  $.ajax(
    {
      type: "POST",
      url: "test2.py",
      data: "stuff_for_python=" + $('#search_text').val(),
      success: function(response)
        {
          $('#python_response').text("Python returned: " + response);
        }
    });
    return false;
  });
</script>

#second function

<p id="demo"></p>

<button onclick="urlLocation()">Click here to get URL of the page</p>

<script>
  function urlLocation()
    {
      var loc = location.href;
      document.getElementById("demo").innerHTML=loc;
    }
</script>

</center>
</body>
</html>

Python代码是:

#!/usr/bin/python

import cgi, cgitb 
cgitb.enable()  # for troubleshooting

form = cgi.FieldStorage()
jquery_input = form.getvalue("stuff_for_python", "nothing sent")

print "Content-type: text/html"
print
print jquery_input

对于功能1,用户在搜索框中输入的内容会通过jQuery/AJAX发送到一个Python脚本,然后由jQuery和Python在搜索框下方显示出来。

功能2是使用一个按钮,当点击这个按钮时,会用JavaScript把当前的网页地址显示在按钮下方。

我想弄明白的是,是否可以点击一个按钮,然后让当前的网页地址(功能2)以类似的方式由jQuery和Python显示出来(功能1)?我刚开始学习编程,想弄清楚这些部分是如何结合在一起的。我知道上面的代码单独看起来没什么用,但如果在未来的项目中进行定制,可能会很有帮助。

我在测试环境中使用的是Python 2.7.6和Apache2。

2 个回答

0

我稍微修改了一下答案,以便达到我的目的。最后,我使用的代码是:

<script>
  $("button").click(function(){
  var loc = window.location.href;
  $.post("...", 
  {stuff_for_python: loc},

  function(data, status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});
</script>

为了简单起见,我选择使用弹窗提示,而不是在页面上显示网址。我的主要目的是点击一个按钮(这个按钮会把当前的网址存成一个变量),然后把这个变量发送给Python。

0

让我看看我是否理解你在问什么。

首先,一般来说,建议不要在HTML中直接使用onclick这个属性,而是把HTML和JavaScript分开来写。要让按钮触发点击事件,你可以使用:

document.getElementById("foo").onclick = function_name;

另外,你也可以用jQuery来实现:

$("#foo").click(function_name);

你甚至可以直接在代码里声明你的函数,然后这样做:

$("#foo").click(function() {
    var loc = window.location.href;
    $("#demo").text(loc);

    $.ajax({
        type: "POST",
        url: "...",
        data: {
            stuff_for_python: loc
        },
        success: function(response) {
            // do something with response
        }
    });

});

撰写回答