简体   繁体   English

在 js 文件中未检测到 Django url 模式

[英]Django url pattern is not detected in js file

I'm using main.js file for java script logic in Django project.我在 Django 项目main.js文件用于 java 脚本逻辑。 When i'm writing this logic inside script tag in base.html , it's working as expected.当我在base.html的脚本标签中编写此逻辑时,它按预期工作。 But, if I separate the logic in .js file, i'm getting Uncaught SyntaxError: Unexpected token '% by pointing url: {% url 'like-post' %}, in browser console.但是,如果我将.js文件中的逻辑分开,我会在浏览器控制台中通过指向url: {% url 'like-post' %},得到Uncaught SyntaxError: Unexpected token '%

base.html:基地.html:

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}">

    <script
      src="https://code.jquery.com/jquery-3.5.1.js"
      integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
      crossorigin="anonymous"></script>
    <script src="{% static 'blog/main.js' %}" type="text/javascript"></script>
    <title>Blog</title>

</head>

main.js:主.js:

$(document).ready(function(event){
    $(document).on('click', '#like', function(event){
        event.preventDefault();
        var pk = $(this).attr('value');
        $.ajax({
            type : 'POST',
            url : {% url 'like-post' %},
            data : {'id' : pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, 
            dataType : 'json',
            success : function(response){
                $(".like-section").load(" .like-section")
                   
            },
            error : function(rs, e){
                console.log(rs.responseText); 
            },
        });
    });
});

I have few other js logic in main.js file, it's working as expected if i comment out above portion in main.js file.我在 main.js 文件中几乎没有其他 js 逻辑,如果我在main.js文件中main.js上面的部分,它会按预期工作。

create another folder and name that as "static".创建另一个文件夹并将其命名为“静态”。 Inside that paste the.js file.在里面粘贴 .js 文件。 Then in base.html file, {% load static %}.然后在 base.html 文件中,{% load static %}。 You are all done.你都完成了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM