如何在哈巴狗模板中发送Ajax请求?

Web*_*per 2 javascript ajax 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'
    });
  })()
Run Code Online (Sandbox Code Playgroud)

但这不起作用,怎么办?我想知道如何在pug文件的嵌入式javascript中发送ajax请求

S4b*_*beR 6

对我来说似乎有两个问题

  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
Run Code Online (Sandbox Code Playgroud)