菜小魚初次使用 ajax,想前端提交數據,后端處理后,將結果以彈框的形式展示,在網上查看了好多,不停的調試,終於調通了
html:
1 <html> 2 <head></head> 3 <body> 4 <form class="formXXX1" method="post"> 5 <br class="formXXX2" /> 6 <div class="form-group"> 7 <label for=" 8 telephone14">手機號: <input class="form1" type="iphone" id="a" name="a" maxlength="11" placeholder="請輸入11位合法手機號" /> </label> 9 </div> 10 <div class="example-box"> 11 <label> 環境:</label> 12 <label class="radio"> <input type="radio" id="b" name="b" value="0" checked="" /><span>b1</span> </label> 13 <label class="radio"> <input type="radio" id="b" name="b" value="1" /><span>b2</span> </label> 14 </div> 15 <br /> 16 <div class="form-group"> 17 <button class="btn btn-primary" type="button" id="notify">提交</button> 18 </div> 19 </form> 20 </body> 21 </html>
js:
1 //路徑根據實際路徑填寫 2 <script type="text/javascript" src="static/js/jquery.min.js"></script> 3 4 <script type = "text/javascript" > 5 $('#notify').on('click', 6 function() { 7 //取變量 8 var b= $("input[name='b']:checked").val(); //單選框取值 9 var a= $('#a').val(); 10 var data = { 11 data: JSON.stringify({ 12 'a': a, 13 'b': b 14 }), 15 } 16 17 //小於11位提示 18 if (a.length != 11) { 19 alert('手機號小於11位,請重新輸入'); 20 return; 21 } 22 23 //ajax 提交數據 24 25 $.ajax({ 26 type: "POST", 27 dataType: "json", 28 url: "/aaa",//后端請求 29 data: data, 30 success: function(result) { 31 console.log(result); 32 { 33 alert('3333' + result); 34 } 35 }, 36 error: function (result) { 37 console.log(result); 38 { 39 alert(result); 40 } 41 } 42 }); 43 44 }) 45 46 </script>
flask:
1 @app.route('/aaa',methods=['POST']) 2 def aaa(): 3 data = json.loads(request.form.get('data')) 4 a= data['a'] 5 b= data['b'] 6 print (a,b) 7 # msg = bbb(a, b)#調用 bbb方法拿返回值 8 msg =a,b 9 return jsonify(msg)
圖例: