nodejs与ajax交互,alert返回数据失败
发布于 9 年前 作者 zhouyix 4454 次浏览 最后一次编辑是 8 年前 来自 问答

渲染模板采用ejs <!DOCTYPE html>

<html> <head> <title><%= title %></title> <link rel=‘stylesheet’ href=’/stylesheets/style.css’ /> <script type=“text/javascript” src="/javascripts/jquery-1.9.1.min.js">

$(function(){ $("#submit").click(function(){

        var params ={
            name: $("#name").val(),
            password: $("#password").val()
        };
		
        $.ajax({
            data: params,
            url: '/',
            type:'post',
            dataType: 'json',
            success: function(data){
                //var data = $.parseJSON(data);
                $("#name").val(data.message);
                alert(data.message);
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert('error ' + textStatus + " " + errorThrown);  
            }
        });
  });

});

</script> </head> <body>

<h1><%= title %></h1>
<p>Welcome to <%= title %></p>

<form method="post">
<input type="text" id="name"/>
<input type="text" id="password"/>
<input type="submit" id="submit" name="提交"/>
</form>

</body> </html>

希望提交后,name的值为我返回的数据 nodejs后台为

router.get(’/’, function(req, res, next) { res.render(‘index’,{title:“ajax test”}); });

router.post(’/’,function (req,res){ console.log(req.body); if(req.body.name!=’’&& req.body.password!=’’){ res.json({message:1}); } }); 点击只会跳转到显示{message:1}的页面,不能返回到原来的页面,并且弹出alert 应该怎么改呢

4 回复

因为你的submit是在form里, 点击后, 实际上走的是form action, 自然就会跳转页面咯. 试试在click时加上e.prevDefault()e.stopPropagation()

@kiliwak 我把form的提交去掉后就好了,谢谢。我有个疑问就是 如果form表单中有action,然后表单中的提交按钮onclick方法又是ajax跳转到不同页面,那点击时如何跳转呢

@zhouyix 1楼已经告诉你答案了,不过应该是e.preventDefault()吧:$(“#submit”).click(function(e){ e.preventDefault();… },在ajax的回调函数里执行跳转就可以了

type=submit ==> type=button res.json( { success: { message:1 } } );

回到顶部