【问题标题】:How to do equivalent of Flask Safe in ajax call如何在 ajax 调用中做相当于 Flask Safe
【发布时间】:2018-11-29 16:00:43
【问题描述】:

我似乎无法在我的 Ajax 调用中复制等效函数,因为我可以在我的主 HTML 页面上使用常规 Javascript。我使用 Python/Flask 作为后端。有没有类似的方法来使用 {{ 变量 |在 AJAX 中使用安全的 }} 语法来获得类似的结果?

我的 sample.py 类

class Sample:
    def __init__(self):
        self.product = 'something'
    def transfer_to_js(self):
        return json.dumps(self.__dict__)

我的烧瓶功能

@app.route('/get_data')
def get_data():
    sample = Sample()
    sample_str = sample.transfer_to_js()
    return jsonify(result=sample_str)

HTML/js(我达到预期结果的地方)

<script>
    console.log({{ result|safe }});
    <!-- returns {product:"Something"} -->
</script>

我的 AJAX 调用(我未能达到预期的结果)

$.getJSON('/get_data', {}, 
    function(data) {
        console.log(data.result); // returns {"product":"Something"}

使用此结果的调用

function printObject(obj){
    console.log(obj['product']); // prints "Something" for regular JS call, prints undefined for AJAX call
}

因此,我相信差异是微妙的,即字典键中的引号与缺少引号,但这足以导致 printObject 函数失败。有没有办法在 python 函数之外处理这个问题(因为我打算从常规的 js 函数和 AJAX 调用中调用这个函数)?

【问题讨论】:

    标签: javascript python json ajax flask


    【解决方案1】:

    原来在 AJAX 调用中,结果是作为字符串而不是 JSON 对象传回的,因此,为了转换它,我写了这个

    $.getJSON('/get_data', {}, 
        function(data) {
            console.log(JSON.parse(data.result)); 
        }
    

    我的结果符合预期

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      相关资源
      最近更新 更多