我尝试在ajax发布后重定向到新页面,但我还没有成功。
我的模板如下所示:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var selectedForm = 0;
function doWork() {
var response = $('#reply1').val();
console.log(response);
$.post({url: "receiver", data: JSON.stringify({selectedForm: selectedForm, response : response}),
contentType: "application/json", success: function(){}});
}
$('.respondButton').click(function(e) {
e.preventDefault();
var selectedButton = $(this).attr('id');
selectedForm = selectedButton.replace('response', '');
console.log(selectedForm);
});
$('#submitButton1').click(function(e) {
e.preventDefault();
doWork();
});
});
</script>
Html部分:
<a id="response1" href="" class="respondButton">
<span>response1</span>
</a>
<a id="response2" href="" class="respondButton">
<span>response2</span>
</a>
<form action="/receiver" method="post" id="form1" name="form1">
<textarea type="text" rows ="3" name="reply1" id="reply1"></textarea>
<button type="submit" name="submitButton1" id="submitButton1">Submit</button>
</form>
在服务器端烧瓶应用程序看起来像这样:
#!flask/bin/python
import sys
from flask import Flask, render_template, request, redirect, Response, url_for
import random, json
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/somepage')
def somepage():
return 'Success'
@app.route('/receiver', methods = ['POST'])
def worker():
data = request.get_json()
result = ''
result = str(data)
print(result)
return (redirect(url_for('somepage')))
if __name__ == '__main__':
app.run(debug=True)
当我打开Chrome开发者工具并点击网络时,它看起来不错,我可能会看到成功消息,但stil浏览器不会重定向到/somepage
答案 0 :(得分:3)
正如我在您的烧瓶应用程序中看到的那样,您尝试输出数据并重定向到主页,但应用程序将执行输出部分,该部分是消息,不会继续重定向, 如果你需要进行重定向,你应该在ajax调用中进行。
success: function(){
window.location.href = "somepage";
}