Web2py:将变量从视图传递给控制器 [英] Web2py: Pass a variable from view to controller

查看:78
本文介绍了Web2py:将变量从视图传递给控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将JavaScript变量从视图传递到控制器中的Python?我不想使用 request.vars request.args ,因为这样可以让用户随意通过在地址栏中键入操作的参数。

How can I pass a JavaScript variable from the view to Python in controller? I don't want to use request.vars or request.args, because that would allow to user to give arbitrary parameters for the action by typing it into the address bar.

示例视图:

<button onclick='myFunction();'>Execute</button>
<script>
    function myFunction();{
        var value = calculateValue();
        //pass value to my_action
        window.location = 'my_action';
    }
</script>

示例控制器:

def index():
    return dict()

def my_action():
    #retrieve passed variable
    #handle the variable 
    #...
    redirect(URL('index'))


推荐答案

您可以拨打Ajax电话:

You could make an Ajax call:

<script>
    function myFunction();{
        var value = calculateValue();
        ajax('{{=URL('default', 'my_action')}}' + '?value=' + value, [], ':eval');
    }
</script>

返回Ajax响应后跟随客户端重定向:

Followed by a client-side redirect once the Ajax response is returned:

def my_action():
    value = request.vars.value
    # handle the variable 
    redirect(URL('index'), client_side=True)

但请注意,即使使用此方法,仍有人可以向 / default / my_action?value = some_value 发出手动请求,向您的函数发送任意数据(当然,他们必须更加精通技术才能这样做,因为上述URL永远不会出现在浏览器地址栏中供他们观察 - 他们必须检查您的代码或观察网络流量以确定要做出的请求。

Note, however, that even with this method, someone could still make a manual request to /default/my_action?value=some_value to send arbitrary data to your function (of course, they would have to be a little more technically savvy to do so, as the above URL would never appear in the browser address bar for them to observe -- they would have to inspect your code or watch the network traffic to figure out what request to make).

通常,如果您在浏览器中计算一个值,然后通过HTTP请求将其提交给服务器,则无法阻止知识渊博的攻击者提交一些任意数据而不是值计算d由您的Javascript代码。您最好的选择是专注于对输入数据进行服务器端验证,或将计算结果移至服务器(尽管可能是计算基于某些输入,这些输入最终必须来自浏览器,因此需要以某种方式进行验证)。

In general, if you are calculating a value in the browser and then submitting it to the server via an HTTP request, there is no way to prevent a knowledgeable attacker from submitting some arbitrary data rather than the value calculated by your Javascript code. Your best bet is to instead focus on doing some server-side validation of the input data, or move the calculation to the server (though presumably the calculation is based on some input that must ultimately come from the browser and therefore be validated in some way).

这篇关于Web2py:将变量从视图传递给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆