最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to make action on node.js server after button click using jQuery AJAX - Stack Overflow

programmeradmin0浏览0评论

I have a problem. I want to make server do something after clicking on button. This is my HTML code:

    <input name="like" id="like" value="Like" type="submit" />
    <script>
        $('like').click(function(){
            $.post('/test')
        });
    </script>

and this is my server-side code:

app.post('/test', function (req, res) {
    console.log('works');
});

And it doesn't work.

I have a problem. I want to make server do something after clicking on button. This is my HTML code:

    <input name="like" id="like" value="Like" type="submit" />
    <script>
        $('like').click(function(){
            $.post('/test')
        });
    </script>

and this is my server-side code:

app.post('/test', function (req, res) {
    console.log('works');
});

And it doesn't work.

Share Improve this question asked Jul 25, 2014 at 12:51 kuba12kuba12 2651 gold badge4 silver badges15 bronze badges 4
  • it should be saying something ? – Mritunjay Commented Jul 25, 2014 at 12:52
  • Well, what do you expect? – morkro Commented Jul 25, 2014 at 12:52
  • 1 can it be $('#like').click(function(){ instead of $('like').click(function(){ – prava Commented Jul 25, 2014 at 12:53
  • Thanks prava I missed # :D – kuba12 Commented Jul 25, 2014 at 12:54
Add a comment  | 

2 Answers 2

Reset to default 8

Your problem is here, you have forgotten the # for targeting element by id, so click would never be invoke.

$('#like').click(function(){
    $.post('/test');
});

It looks like you aren't selecting the input tag correctly. If you want to select a DOM element by ID, you'll want to use '#IDname' as your selector.

For this example, that means changing it to

...
$('#like').click(function(){
...

This also might not fix the error entirely: using a an input field with a type of "submit", you will likely have to do something like this:

...
$('#like').click(function(e){
    e.preventDefault();
...

to keep the default submit event on the input from "bubbling up."

发布评论

评论列表(0)

  1. 暂无评论