【问题标题】:passing value through AJAX url attribute to server code通过 AJAX url 属性将值传递给服务器代码
【发布时间】:2021-01-19 17:53:38
【问题描述】:

我正在构建一个非画布覆盖以显示博客上的所有 cmets。我想使用 ajax,这样用户就可以在不重新加载页面的情况下发布和查看 cmets 部分的更新。

我一直在为我的 HTML 文件使用 ejs 语法,但是当它转到 ajax 时,我不知道如何让后端服务器通过 ajax 中的“erl”属性识别数据。

我的 ajax 代码

$("#commentBtn").on("click", () => {
        $.ajax({
            url: "/home/<%=blog.title%>/comment",    <--- I want to send the title attribute of the blog to backend
            contentType: "application/json",
            success: (response) => {
                let commentElem = $("#showComments");

                response.comments.forEach(comment => {
                    commentElem.append('\
                        <h2>'+comment.id+'</h2>\
                        <h3>'+comment.content+'</h3>\
                    ');
                });
            }
        })
    })

相关的HTML代码

<button type="button" id="commentBtn" uk-toggle="target: #offcanvas-usage">show comment</button>

我的路由器

router.get("/home/:title/comment", async(req, res) => {
    await Blog.findOne({title: req.params.title}, (err, foundBlog) => {
        if(err) {
            console.log(err);
        } else{
            *do the send comment things ....*
        }
    })
})

现在的问题是路由器无法识别req.params.title,我认为是ajax问题,它没有将博客标题发送到路由器。这样路由器就找不到我的具体博客了。

是否有任何 ajax 语法让我的路由器使用req.params.title

提前致谢!

【问题讨论】:

  • jQuery代码显示在ejs文件还是js文件中?
  • jquery代码在js文件中
  • 那你需要另一种方式将标题传递给js文件。它不会被 ejs 编译。检查浏览器开发工具网络中发出的实际请求,您会看到它包含文字字符串 "&lt;%=blog.title%&gt;" 而不是变量值
  • 明白,谢谢!我将尝试找到一种将博客标题传递给我的 js 文件的方法。或者,如果您能给我指点方向,我也将不胜感激!
  • 一种方法是在 ejs 文件中使用一个简单的脚本标记和一个 javascript 变量,然后您可以使用该变量在 js 文件中的 url 中进行连接。对应用的其余部分了解不足,无法采取更全面的方法

标签: javascript jquery node.js ajax ejs


【解决方案1】:

我不熟悉ejs,但是你能用模板文字吗?

url: `/home/${blog.title}/comment`

更多信息here

【讨论】:

    猜你喜欢
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 2012-07-07
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多