【问题标题】:my data is not posting to django rest api using ajax我的数据没有使用 ajax 发布到 django rest api
【发布时间】:2021-04-09 03:26:53
【问题描述】:

不知何故,我的数据没有发布到 /api/recipe/recipes/ 我的 html

    {% extends 'base.html' %}
    {% block content %}
    <!DOCTYPE html>
    <html>
    
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>Create a Recipe</title>
    </head>
    
    <body class="">
      <form>
        {% csrf_token %}
        <br>
        <label for="T">Title: </label>
        <input type="text" name="T" value="">
        <br>
        <label for="Ingr">Ingredients: </label>
        <select class="" name="Ingr">
          {% for ing in Ing %}
          <option value="ing.pk">{{ing}}</option>
          {%endfor%}
        </select>
        <br>
        <label for="Tag">Tags: </label>
        <select class="" name="Tag">
          {% for tag in Tag %}
          <option value="Tag.pk">{{tag}}</option>
          {%endfor%}
        </select>
        <br>
        <label for="Time">Time: </label>
        <input type="text" name="Time" value="">
        <br>
        <label for="P">Price: </label>
        <input type="text" name="P" value="">
        <br>
        <label for="link">Link: </label>
        <input type="text" name="link" value="">
        <br>
        <input type="submit" name="submit" value="Post">
      </form>
      <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
      <script>
       $('form').on('submit', function(e) {
    e.preventDefault()
      var data = {
        title: $('[name="T"]').val(),
        tags: $('[name="Tag"]').val(),
        ingredients: $('[name="Ingr"]').val(),
        time_minutes: $('[name="Time"]').val(),
        price: $('[name="P"]').val(),
        link: $('[name="link"]').val()
      };

      var headers = {
        'X-CSRFToken': '{{ csrf_token }}'
      }; // Inject our token into the javascript using a template tag
      $.ajax({
        type: 'POST',
        data: data,
        headers: headers, // Set the headers in the request
        url: '/api/recipe/recipes/',
        success: function(res) {
          console.log(res)
        },
      });
  })
      </script>
    </body>
    
    </html>
    {%endblock%}

我正在尝试将此表单发布到上面 URL 中的其余框架中,如果您有任何解决方案,请帮助我提前感谢您

我在提交时在控制台中收到这些错误

Uncaught TypeError: $.ajax is not a function
    at HTMLFormElement.<anonymous> ((index):101)
    at HTMLFormElement.dispatch (jquery-3.1.1.min.js:3)
    at HTMLFormElement.q.handle (jquery-3.1.1.min.js:3)

这 3 个错误对我来说是一场噩梦,我尝试了很多方法,但都没有奏效,我真的很感激任何帮助:D

【问题讨论】:

  • 一个问题是您需要在此&lt;script src="https://code.jquery.com/jquery-3.1.1.min.js"&gt; 之后关闭&lt;/script&gt; 标记
  • 它没有解决我的错误我看到人们使用类似这样的东西 $(document).on("click",'.shares', function (event) { 这行得通吗?如果可以你在我的代码上做吗?谢谢,
  • 如果您完全删除&lt;script src="https://code.jquery.com/jquery-3.1.1.min.js"&gt;&lt;/script&gt; 会怎样?我想知道两次导入 jquery 是否会导致问题。
  • 很遗憾,它没有用
  • 那我很难过。如果我导入脚本和console.log(typeof $.ajax),它会显示“函数”

标签: javascript html jquery ajax rest


【解决方案1】:

我希望这与您引用库的方式有关,在此处模拟您的代码是可行的(好吧,无论如何它都会发出请求)。导入同一个库的多个版本可能会导致麻烦,但我不确定它是否会给出您遇到的错误。在这个例子中,我从你的代码中去掉了迭代 django 上下文变量,但是这些应该与你遇到的问题没有任何关系。

$('form').on('submit', function(e) {
  e.preventDefault()
  var data = {
    title: $('[name="T"]').val(),
    time_minutes: $('[name="Time"]').val(),
    price: $('[name="P"]').val(),
    link: $('[name="link"]').val()
  };

  var headers = {
    'X-CSRFToken': '{{ csrf_token }}'
  }; // Inject our token into the javascript using a template tag
  
  $.ajax({
    type: 'POST',
    data: data,
    headers: headers, // Set the headers in the request
    url: '/api/recipe/recipes/',
    success: function(res) {
      console.log(res);
    },
    error: function(res) {
      var errorMessage = res.status + ': ' + res.statusText;
      console.error('Error Posting: ', errorMessage);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <br>
  
  <label for="T">Title: </label>
  <input type="text" name="T" value="">
  <br>
  
  <label for="Time">Time: </label>
  <input type="text" name="Time" value="">
  <br>

  <label for="P">Price: </label>
  <input type="text" name="P" value="">
  <br>
  
  <label for="link">Link: </label>
  <input type="text" name="link" value="">
  <br>
  
  <input type="submit" name="submit" value="Post">
</form>

【讨论】:

  • 这里不起作用是我的完整代码github.com/osamada/recipe-app-api.git
  • 我设法通过将脚本标记更新为 jquery 来使其工作:&lt;script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"&gt;&lt;/script&gt; 我直接从 jquery 网站code.jquery.com 获得了这个脚本标记并单击缩小链接
  • 非常感谢错误消失了,但我的数据仍然没有发布到其余框架
  • 我最终将大部分脚本移至 head 块。以前建议将脚本放在body 的末尾,但我觉得这在很大程度上是过时的建议,我建议查看asyncdefer script 属性代替(尽管我在测试中都没有使用因为他们没有工作)。我还在 docker-compose.yml 文件中的 runserver 命令之前添加了 python manage.py collectstatic &amp;&amp;,只是为了确保在每次启动时收集所有自定义 django 模板(我只是按照标准这样做)。
【解决方案2】:

我终于解决了,我的 base.html 中有另一个 jquery 脚本,这就是为什么它不起作用我删除了它,现在它可以工作了,感谢大家帮助我

【讨论】:

    猜你喜欢
    • 2015-10-08
    • 2020-12-07
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多