express发出post请求而不从当前页面重定向

express发出post请求而不从当前页面重定向

本文介绍了node.js / express发出post请求而不从当前页面重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个node.js表达应用程序,它试图发布一个post请求并查询数据库的内容。我正在尝试执行发布请求,而无需从表单页面重定向用户或重新加载页面。

I have a node.js express application which is trying to make a post request and query the contents of a database. I am trying to execute the post request without have to redirect the user from the form page or reloading the page.

index.jade

index.jade

form.well(id="newEntryForm", method="post", action="/addEntry")
    label Key:
    br
    input(name="key", id="key", class="new-entry", type="textbox")
    br
    br
    label Value:
    br
    input(name="value", id="value", class="new-entry", type="textbox")
    br
    br
    button.btn(type="submit") Add Entry

app.js

app.post('/addEntry', function(req, res){
   //database query
});

这最终会将我重定向到URL localhost:3000 / addEntry 。我知道我可以在post方法的回调中添加 res.redirect(/); ,但这会重新加载页面。如何在不重新加载页面的情况下完成此操作?

This ends up redirecting me to the URL localhost:3000/addEntry. I know I can add res.redirect("/"); within the callback for the post method, but that will reload the page. How do I accomplish this without reloading the page?

编辑

我添加了在提交表单时执行的javascript方法,但最终会在URL栏上附加POST请求参数。我该如何避免这种情况?

I added a javascript method to execute on submitting the form, but it ends up appending the POST request parameters on the URL bar. How do I avoid this?

Javascript方法

Javascript method

$(function() {
    $('#newEntryForm').submit(function() {
        var data = {key: 'a', value: 'b'};
        // build a json object or do something with the form, store in data
        $.post('/addRule', data, function(resp) {
            alert(resp);
            console.log("post response: " + resp);
            // do something when it was successful
        });
    });
});


推荐答案

正如评论所说,你需要使用客户端的JavaScript + AJAX。

As a comment said, you need to use client side javascript+ajax.

$(function() {
    $('#newEntryForm').submit(function(event) {
        event.preventDefault(); // Stops browser from navigating away from page
        var data;
        // build a json object or do something with the form, store in data
        $.post('/addEntry', data, function(resp) {
            alert(resp);
            // do something when it was successful
        });
    });
});

这篇关于node.js / express发出post请求而不从当前页面重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 06:17