将JavaScript变量传递给Python
例如:
#!/usr/bin/python
print "This is python."
print "<script type="text/javascript">
var pass_to_python = new Number(7)
</script>"
the_number = pass_to_python???
我该如何在Python中获取pass_to_python?
5 个回答
3
我正在使用Flask和Ajax将值从JavaScript传递到Python。
function pass_values() {
var pass_to_python = new Number(7)
$.ajax(
{
type:'POST',
contentType:'application/json;charset-utf-08',
dataType:'json',
url:'http://127.0.0.1:5000/pass_val?value='+pass_to_python ,
success:function (data) {
var reply=data.reply;
if (reply=="success")
{
return;
}
else
{
alert("some error ocured in session agent")
}
}
}
);
}
Python代码:
@app.route('/pass_val',methods=['POST'])
def pass_val():
name=request.args.get('value')
print('name',name)
return jsonify({'reply':'success'})
3
你可以通过 GET
或 POST
方法来请求一个 Python 脚本。如果你想要动态地进行这个操作,可以使用 AJAX。
这里有个不错的链接: Python 中如何处理 POST 和 GET 变量?
5
使用pyv8,你可以在Python中执行JavaScript代码。
import PyV8
class Global(PyV8.JSClass):
pass
with PyV8.JSContext(Global()) as ctxt:
the_number = ctxt.eval("var pass_to_python = new Number(7)")
可以查看这个链接了解更多信息:http://code.google.com/p/pyv8/