2014-07-03 91 views
1

我試圖讓一些JavaScript運行一個函數來更新一個合理的大json字典輸入的值,然後我想在它的後端得到它的保留。所以我有以下的HTML和javascript:通過Flask發送POST數據

<head> 
<!--some info here --> 
<script> 
     function AddPostData() { 
      var data = editor.getValue(); 
      //this editor.getValue() gets the json string and it is working 
      //as validated by an alert message 

      var formInfo = document.forms['json_form']; 
      formInfo.elements["json_data"].value = data; 
      alert(data) 
     } 
    </script> 
    </head> 
    <body> 

    <!-- I have the json editing GUI here --> 

    <form id="json_form" method="POST" action="/test"> 
     <input type="hidden" name="json_data" value="" /> 
     <input type="submit" value="Submit" onclick="AddPostData();"> 
    </form> 

然後這裏是我的燒瓶的Python。

@app.route('/test', methods=['GET', 'POST']) 
def test(): 
    if request.method == 'POST': 
     print (request.data) 
     the_json=request.data 
     #this template simply prints it out and all that I get is b" 
     return render_template('testing.html', the_json=the_json) 

任何想法發生了什麼問題?當我將一個字符串硬編碼到數據變量中時,我仍然沒有在request.data字段中獲取任何內容。那麼確切我得到AB後跟一個報價:B」

我想這是一些錯誤的,因爲它實際上並沒有把JSON到輸入的值字段

回答

1
the_json = request.form.get('json_data', None) 

代替。的

the_json=request.data 

將在硬編碼的部分工作(是肯定的,但我也不太清楚,如果你的Java腳本作品/不是我的專業領域,但它看起來OK)。

+0

咦我想這是什麼問題JavaScript,但實際上這是問題。 – clifgray

1

取決於Content-Type

Content-Type: application/json 

情況下,你可以使用

request.get_json() 

,並在

Content-Type: application/x-www-form-urlencoded (like what you wanted to do) 

情況下,你可以使用

# to get all the items 
dict(request.form.items()) 
# to specific item from post data 
request.form.get("json_data")