简体   繁体   中英

How can I send a POST request without data in Java Script

So I am already using Ajax to send an array to the router as you could see here...

 var send = function () {
            var data = search
            console.log(data)
            $.ajax({
                type: 'post',
                url: "/next",
                data: JSON.stringify(data),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    console.log('Success')
                },
                error: function (err) {
                    console.log(err)
                }
            })
        }
        send();

If I console.log this as

console.log(req.body)

I get

[ 'Faye Dunaway', 'Kathy Bates' ]

which is fine, I need this. However, in my router I am also trying to render a new page with data in it like this....

router.post("/next", function (req, res) {
    Movies.find({name:{ $in: req.body}}, function(err, found){
        if(err){
            console.log(err)
        } else {
            res.render('movies',{
                movies:found
            })
        }
    })
})

Now I have been told that I can not call res.render with ajax so I needed to make a button inside a form.

<form action="/next" method="post">
    <button  class="btn btn-outline-success btn-lg next">next</button>
 </form> 

However, if I console.log req.body now i get

[ 'Faye Dunaway', 'Kathy Bates' ]
{}

So I am thinking 2 things, either res.render has to be called with ajax or I need to get rid of the {}. As you can tell I am new to this. Thank your for your help. Ask for any additional information.

As far as i know, data passed on render is not in body but used in templating engine. So you can access it inside script block of your templating engine (PUG) like this.

script.
    !{movies}

If you want to access the data throught bundled script (created with webpack), you have to define it in templating like this.

script.
    const movies = !{movies}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM