[英]Avoid redirect in post request
I'm trying to display a contents of a JSON that I receive from the backend onto the frontend without redirecting to a new page.我正在尝试显示从后端接收到的 JSON 的内容,而不重定向到新页面。
I want to avoid redirecting in this POST request, but it automatically goes to the URL search_results/ and prints out the json.我想避免在这个 POST 请求中重定向,但它会自动转到 URL search_results/ 并打印出 json。 How can I avoid this?
我怎样才能避免这种情况?
It does, however, print out on the console "Success in redirect post" before redirecting.但是,它确实会在重定向之前在控制台上打印出“重定向帖子成功”。
$(document).ready(function () {
$.extend(
{
redirectPost: function(location, args)
{
var form = $('<form></form>');
form.attr("method", "post");
form.attr("action", location);
$.each( args, function( key, value ) {
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", value);
form.append(field);
});
$(form).appendTo('body').submit();
}
});
$("#submitButton").click(function() {
console.log("submitButton clicked")
$("#search_form").submit(function(e) {
e.preventDefault();
$.redirectPost("./search_results/", {
inheritance: $("input[name=inheritance]:checked").attr("id"),
penetrance: $("input[name=penetrance]:checked").attr("id"),
mortality: $("input[name=mortality]:checked").attr("id"),
success: function(response){
console.log("Success in redirect post!")
var json_results_list = response.body.results_list
}
});
});
});
});
My backend code looks something like this:我的后端代码如下所示:
app.post('/search_results', callName)
function callName(request, response) {
//...insert serverside code..
//...set global_data to a JSON in string form
response.send(JSON.parse(global_data))
}
So basically what you want is called ajax.所以基本上你想要的叫做ajax。 You don't need to create the
redirectPost
method which will make a invisible form and them submit it.您不需要创建将制作一个不可见的表单并提交它的
redirectPost
方法。 Just use $.post
instead.只需使用
$.post
代替。
$.post("./search_results/", {
inheritance: $("input[name=inheritance]:checked").attr("id"),
penetrance: $("input[name=penetrance]:checked").attr("id"),
mortality: $("input[name=mortality]:checked").attr("id")
}, function (response) {
console.log("Success in redirect post!")
var json_results_list = response.body.results_list
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.