2016-08-25 72 views
0

我有一個非常簡單的HTML表單,只有一個<input type='text'>字段,一個電子郵件地址,我需要通過AJAX傳回Python腳本。我似乎無法接受另一端的價值。 (而且可以將所有的JSON編碼/解碼來避免,因爲這只是一個場?)通過AJAX通過一個字段Flask

下面的代碼:

from flask import Flask, render_template, request, json 
import logging 

app = Flask(__name__) 

@app.route('/') 
def hello(): 
    return render_template('index.htm') 

@app.route('/start', methods=['POST']) 
def start(): 
    # next line outputs "[email protected]" 
    app.logger.debug(request.json); 
    email = request.json['email']; 
    # next line ALSO outputs "[email protected]" 
    app.logger.debug(email); 
    return json.dumps({ 'status': 'OK', 'email': email }) 

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

和JavaScript從HTML side--

發送AJAX
$("form").on("submit", function(event) { 
    event.preventDefault(); 

    d = "email=" + $('#email').val(); // this works correctly 

    // next line outputs 'sending data: [email protected]' 
    console.log("sending data: "+d); 

    $.ajax({ 
     type: "POST", 
     url: "{{ url_for('start') }}", 
     data: JSON.stringify(d), 
     dataType: 'JSON', 
     contentType: 'application/json;charset=UTF-8', 
     success: function(result) { 
      console.log("SUCCESS: "); 

      // next line outputs 'Object {email: "[email protected]", status: "OK"}' 
      console.log(result); 
     } 
    }); 
}); 

回答

1

JSON.stringify用於將對象轉換爲JSON格式的字符串,但沒有對象,只是一個字符串。試試這個:

var d = { email: $('#email').val() }; 

JSON.stringify(d)現在把它轉換成一個JSON格式的字符串:

{email: "[email protected]"}可以通過燒瓶解析。


要做到這一點,而不JSON:

var d = { email: $('#email').val() }; 
... 
// AJAX 
    data: d, 
    success: ... 

這將打開{email: "[email protected]"}[email protected]併發送作爲POST請求的身體。在Flask中,使用request.form['email']