本文介绍了将数据从html / js返回到python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由javascript函数填充的html表单。我有另一个javascript函数,它获取所有表单元素的值,并且当前只使用警报将它们显示回用户。使用以下代码通过python显示html页面:

I have an html form which is populated by javascript functions. I have another javascript function which gets the values of all of the form elements, and currently just uses an alert to display them back to the user. The html page is diplayed via python with the following code:

import webbrowser
new = 2 #open new tab if possible
url = "form.html"
webbrowser.open(url, new=new)

这一切都运行良好,但我没有使用警报显示数据,我想将数据传递回python,但不知道如何。所有数据都存储在一个javascript数组中,所以我基本上只需要传递这一段数据。

This all works well, but instead of displaying the data using an alert, I would like to pass the data back to python, but dont know how. All of the data is stored in a javascript array, so I essentially just need to pass this one piece of data.

编辑:我不能使用任何外部库。

I cannot use any external libraries.

推荐答案

>>> import json
>>> weird_json = '{"x": 1, "x": 2, "x": 3}'
>>> x = json.loads(weird_json)
>>> x
{u'x': 3}
>>> y = json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
>>> y
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]

您可以获取HTML数据并将其转换为字典,从而可以执行以下操作:
print x ['x']

You can take the HTML data, and convert it into a dictionary, enabling you to do:print x['x']

这是起点,在Python中创建一个侦听端口的套接字。
然后让它收到数据。

This is the starting point, create a socket in Python which listens to a port.Then have it recieve data.

在Javascript中,打开一个可以连接到端口的套接字(一个Python监听的端口)。
使用说:

In Javascript, open a socket which can connect to a port (the one Python listens to).Use, say: http://socket.io/

这是一个纯粹的socket-to-socket相关问题?





This is a pure socket-to-socket related issue?


from socket import *
import json
s = socket()
s.bind(('', 80))
s.listen(4)
ns, na = s.accept()

while 1:
    try:
        data = ns.recv(8192)
    except:
        ns.close()
        s.close()
        break

    data = json.loads(data)
    print data

你有一个套接字监听80,连接到那个并发送你想要的任何内容。

There you got a socket listening to 80, connect to that and send whatever you want.

function callPython()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","Form-data",true);
xmlhttp.send();
}

例如,您可以将表单数据作为字符串发送,替换表单数据和Python的响应可以放入myDiv:)

For instance, where you can send the form data as a string, replacing "Form-data" and the response from Python can be put into "myDiv" :)

这篇关于将数据从html / js返回到python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 23:42