【问题标题】:Retrieve data from a post method of express with jquery使用 jquery 从 express 的 post 方法中检索数据
【发布时间】:2021-07-23 05:45:39
【问题描述】:

我正在为一个动态网站使用 express.js,我决定使用 jQuery 发送 post 方法,这样我可以创建多个按钮并根据用户在同一页面上按下的按钮发送不同的信息. 这是我的简化环境:

html 文件:

<% if(alert) { %>
<div class="alert info"><i class="fas fa-info-circle"></i> Si tu viens de souscrire à un abonnement, patiente une à deux minutes.</div>
<% } %>

<form>
  <input id="premiumKey" placeholder="Enter your key here !"></input>
  <input id="save-button-key" class="sub save key" type="button" value="Save"></input>     
</form>   

<script type="text/javascript">
    $('#save-button-key').click(function(){  

    let key = document.getElementById("premiumKey").value
   $.ajax({ 
         url: '/profil/premium',
         type: 'POST',
         cache: false, 
         data: { premiumKey: key, input: 2 }, 
         success: function(data){

         }
         , error: function(jqXHR, textStatus, err){

         }
      })
   });            

</script>

express.js 文件:

  const renderTemplate = async (res, req, template, data = {}) => {

    const baseData = {
      bot: client,
      path: req.path,
      user: req.isAuthenticated() ? req.user : null,
    };
    // We render template using the absolute path of the template and the merged default data with the additional data provided.
    res.render(path.resolve(`${templateDir}${path.sep}${template}`), Object.assign(baseData, data));
  };


  app.get("/profil/premium", async (req, res) => {
    
    renderTemplate(res, req, "profil/premium.ejs", { alert: null });
  });

  app.post("/profil/premium", async (req, res) => {
    console.log(req.body)
    console.log(req.body.premiumKey)

    var user = req.user;

    let alert = true;
    renderTemplate(res, req, "profil/premium.ejs", { alert });
  });

我想要什么 当我按下按钮时,我想恢复,我在 express 文件中使用 post 方法得到的警报。我可以显示 ajax 发送到服务器的内容,但我不能在 post 方法中执行相反的操作。例如,我想分析信息,并将结果返回给用户。 到目前为止我做不到。

再次感谢您的帮助。

【问题讨论】:

    标签: javascript html jquery node.js express


    【解决方案1】:

    我建议你,使用 json 发送响应。 而不是渲染模板

    renderTemplate(res, req, "profil/premium.ejs", { alert });
    

    以json格式发送数据

    const alertData = {
    value: 1,
    otherValue: "the alert data"
    };
    res.json(alertData);
    

    然后在前面,在 jquery 中,在 succes 函数中,您将收到数据

    $.ajax({ 
             url: '/profil/premium',
             type: 'POST',
             cache: false, 
             data: { premiumKey: key, input: 2 }, 
             success: function(data){
                console.log(data); // data from the server
                //here you can use the data
    
             }
             , error: function(jqXHR, textStatus, err){
    
             }
          })
       });     
    

    希望能帮到你

    PD。我不太会说英语

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 2014-09-12
      • 1970-01-01
      • 2013-11-09
      • 2019-03-14
      • 1970-01-01
      相关资源
      最近更新 更多