【问题标题】:How to send Ajax request in pug template?如何在 pug 模板中发送 Ajax 请求?
【发布时间】:2017-03-08 14:55:09
【问题描述】:

我想在 pug 模板文件中发送 Ajax 请求。

form#payment-form()
  section
    label(for="amount")
      input#amount(name="amount" type="tel" min="1" placeholder="Amount"                         value="10")
script(src="scripts/jquery.js")
script.
  (function () {
    var amount = $('#amount').val();
     $.ajax({
      type: "POST",
      url: "/posturl",
      data: {'amount':amount},
      success: function(){},
      dataType: 'json'
    });
  })()

但是不行,怎么办? 我想知道如何在 pug 文件的嵌入 javascript 中发送 ajax 请求

【问题讨论】:

    标签: javascript ajax pug


    【解决方案1】:

    对我来说似乎有两个问题

    1. 你在(function (){下的函数中放置了不必要的标签
    2. 您需要使用document.ready 来确保HTML 内容是 准备好。如果您在收到响应后并不真正关心 DOM,则可以避免这种情况

    检查下面的工作示例

    doctype html
    html
      head
        script(src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js')
        script.
          $(document).ready(function(){
          $.ajax({url: "demo_test.txt", success: function(result){
          $("#div1").html(result);
          }});
          });
      body
        #div1
          h2 Let jQuery AJAX Change This Text
    

    【讨论】:

      【解决方案2】:

      这里你的 pug 模板没有问题(也许你可以在 #payment-form() 之后删除 (),因为它是空的并且它不是 mixin)。但是对于您的 JS,您会立即发送 AJAX 请求,您应该将其绑定到一个事件(单击按钮、按下输入等)。然后,您必须确保将您的库 jquery.js 放在您可以通过浏览器使用 scripts/jquery.js 访问的目录中。如果此更改后仍然无法正常工作,请更准确地报告您的错误(打开控制台以获取消息,向我们提供您期望的行为和您得到的行为)。

      【讨论】:

        猜你喜欢
        • 2015-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-31
        • 2021-02-14
        • 1970-01-01
        • 2020-04-05
        • 1970-01-01
        相关资源
        最近更新 更多