【问题标题】:HTML page is not rendered after ajax post in node.js在 node.js 中的 ajax 发布后不呈现 HTML 页面
【发布时间】:2014-05-12 11:03:48
【问题描述】:

我正在使用 express.js。我想做的只是在单击表格元素后重定向到 html 页面。当前输出是 HTML 源代码 console.log(而不是重定向然后解释为 HTML 页面)

我的点击功能如下(ajax post)

<script>    
$(".table").click(function() {



    /* Act on the event */


$.ajax({
    url: "/selectForm",
   type: "POST",
  data: {name : "John"},

cache: false,
timeout: 5000,
complete: function() {
  //called when complete
  console.log('process complete');
  },

success: function(data) {
  console.log(data);
  console.log('process sucess');
 },

error: function() {
  console.log('process error');
},
});

});

我的 app.post 如下所示;

 app.post('/selectForm',function(req,res){


 res.redirect('hello.html');
 });

我在 chrome javascript 控制台中获得了 HTML 输出,但在浏览器中我没有看到它重定向到 hello.html。

【问题讨论】:

  • 我猜你应该在你的$.ajax 请求中插入async: false。然后,您可以根据需要删除 timeout
  • 不走运 async :false 。我可以在控制台日志中看到呈现的 html 页面,然后显示“处理成功”和“处理完成”消息。

标签: jquery ajax node.js express


【解决方案1】:

您的res.redirect('hello.html') 指令不会影响 AJAX 请求。 AJAX 是异步的,因此请求将发送到服务器,响应将返回到浏览器以由您的 JavaScript 解释。

要在 AJAX 请求后重定向到另一个页面,您需要在 console.log('process complete') 指令下方提供额外的指令 (window.location.replace('hello.html'))。

【讨论】:

    【解决方案2】:

    我也遇到了同样的问题,我找到了另一种解决方法~~ 网页 javascript....

    $.ajax({
        url: '/test',
        type : 'POST',
        data: data,
        success : function(ret){
            document.write(ret);
        },
        error: function(err){
            document.write(err.responseText);
        }
    });
    

    而服务器代码是...

    app.post('/test$',function(req,res,next){
         if(req.body.xxx != null){
            res.render('test',{xxx:xxx})
         }else{
            var err = {};
            err.status = 403;
            err.message = 'not allow';
            next(err);
         }
    });
    
    app.use(function(err, req, res, next) {
       res.locals.message = err.message;
       res.render('error');
    });
    

    你可以试试.....

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      • 2019-12-27
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多