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);
}
});
});