字典get方法不使用收到的请求数据

时间:2014-07-28 20:30:17

标签: python ajax flask

我尝试做的是从文本框向服务器发送值。然后在字典中搜索此值并将结果放在 div 中。例如,如果我的词典是d = {'a': "1", 'b': "2", 'c': "3"}而我得到了#34; a"从文本框中它应该在div中写入2。但是找不到该值并返回默认结果。问题是什么?它可能是一些愚蠢的东西,但我无法找到它。这是我的代码:

VIEW

from flask import Flask, render_template, request

app = Flask(__name__)

d = {'a': "1", 'b': "2", 'c': "3"}


@app.route("/", methods=['GET', 'POST'])
def index():
    return render_template('index.html')


@app.route("/demo_test", methods=['GET', 'POST'])
def demo():
    if request.method == "POST":
        data = request.data
        print "dict: {}".format(d)  # I can access the dict from here
        print "res {}".format(d.get("b", "meh"))  #get() is working with a string. Returns "2"
        print "request data: {} type: {}".format(data, type(data))  # I'm receiving data without problems
        ndata = d.get(data, "meh")  # For example if I receive "b" the result is "meh". It should be "2" 
        print "ndata: {} type: {}".format(ndata, type(ndata))
        return ndata

if __name__ == "__main__":
    app.run(debug=True)

HTML

<!DOCTYPE html>
<html>
<head>
<script type=text/javascript
  src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>

    <form action="" method="POST">
        <input type="text" id="selector" name="selector">
    </form>
    <div id="div1"></div>  

  <script type="text/javascript">
    $('#selector').change(function () {
      var value = $('#selector').val()
      $.ajax({
              type : "POST",
              url : "{{ url_for('demo') }}",
              data: JSON.stringify(value),
              contentType: 'text/plain',
              success: function(result) {
                  $('#div1').html(result)
              }
          });
   });
  </script>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

您正在发送 JSON 字符串;这包括报价。因此,您尝试查找'"b"',而不是'b'

>>> import json
>>> json.dumps('b')
'"b"'

最好告诉服务器你发布JSON并在服务器端加载数据:

$.ajax({
    type : "POST",
    url : "{{ url_for('demo') }}",
    data: JSON.stringify({'key': value}),
    contentType: 'application/json',
    success: function(result) {
        $('#div1').html(result)
    }
});

并在服务器端:

if request.method == "POST":
    data = request.get_json()
    ndata = d.get(data['key'], "meh")
    return ndata