python - flask+ajax post 400錯誤
問題描述
表單代碼
<form role='form' action='/tpush/pl' method='post'><p class='input-field col s4'> <input name='cname' type='text' class='validate'> <label for='cname'>Username</label></p><p class='input-field col s4'> <input name='cemail' type='text' class='validate'> <label for='cemail'>Email</label></p><p class='input-field col s4'> <input name='curl' type='text' class='validate'> <label for='curl'>URL</label></p><i class='material-icons prefix'>mode_edit</i><label for='comment-textarea'>評論</label><textarea name='comment'></textarea><p style='z-index: 100'></p><button type='reset'>取消</button><button type='submit'>確認保存</button> </form> <p id='res'></p>
ajax代碼:
<script type='text/javascript'> $(function(){ $(’.btn’).click(function(){ var $cname = $(’input[name='cname']’).val(); var $cemail = $(’input[name='cemail']’).val(); var $curl = $(’input[name='curl']’).val(); var $text = $(’textarea[name='comment']’).val(); var $res = $(’#res’); $.ajax({ url:’/tpush/pl’, data: $(’form’).serialize(), type: ’POST’, dataType:’json’ }).done(function (data) { if (!data.r){ $res.html(data.rs); }else{ $res.html(data.error); } }); }); });</script>
python代碼
@web.route(’/tpush/pl’,methods=[’POST’])def web_tpush(): cname = request.form[’cname’] cemail = request.form[’email’] curl = request.form[’curl’] #ctext = request.form[’ctext’] print(cname,cemail,curl) error = None if len(cname) < 2:error = ’666’ if len(cemail) < 5:error = ’777’ if error is not None:return jsonify({’r’:1,’error’:error}) return jsonify({’r’:0,’rs’:ok})
我點擊提交后跳轉到/tpush/pl 提示:
4000 Bad RequestThe browser (or proxy) sent a request that this server could not understand.127.0.0.1 - - [13/May/2017 19:57:42] 'POST /tpush/pl HTTP/1.1' 400 -127.0.0.1 - - [13/May/2017 19:57:42] 'POST /tpush/pl HTTP/1.1' 400 -
問題解答
回答1:cemail = request.form[’email’]
改為
cemail = request.form[’cemail’]
另外,你的form里有默認post 提交。如果想要自己處理的話,就不要在form里外加action 了。
$(’.btn’).click(function(event){ event.preventDefault();});
相關文章:
1. 在應用配置文件 app.php 中找不到’route_check_cache’配置項2. html按鍵開關如何提交我想需要的值到數(shù)據(jù)庫3. HTML 5輸入框只能輸入漢字、字母、數(shù)字、標點符號?正則如何寫?4. javascript - 請教如何獲取百度貼吧新增的兩個加密參數(shù)5. Android中能不能判斷一個數(shù)據(jù)庫是create來的,還是open來的?6. gvim - 誰有vim里CSS的Indent文件, 能縮進@media里面的7. 跟著課件一模一樣的操作使用tp6,出現(xiàn)了錯誤8. PHP類屬性聲明?9. javascript - 求助canvas繪制馬賽克的問題,老是取色不準10. java - 安卓接入微信登錄,onCreate不會執(zhí)行
