表单代码
<form class="row" role="form" action="/tpush/pl" method="post">
<p class="input-field col s4">
<input id="cname" name="cname" type="text" class="validate">
<label for="cname">Username</label>
</p>
<p class="input-field col s4">
<input id="cemail" name="cemail" type="text" class="validate">
<label for="cemail">Email</label>
</p>
<p class="input-field col s4">
<input id="curl" 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 id="comment-textarea" class="materialize-textarea OwO-textarea" name="comment"></textarea>
<p class="OwO" style="z-index: 100"></p>
<button class="btn btn-white" type="reset">取消</button>
<button id="submit_button" class="btn btn-primary" 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 Request
The 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 -
改为
另外,你的form里有默认post 提交。如果想要自己处理的话,就不要在form里外加action 了。