【问题标题】:Append data to form using through DOM?通过 DOM 将数据附加到表单?
【发布时间】:2022-02-11 03:30:44
【问题描述】:

使用 POST 方法的表单:

<div>
<form action="{{ route('post.store') }}" method="POST">
   <input type="text" name="name">
   <input type="text" name="text">
   <button type="submit">Submit</button>
</form>
@foreach ($comments as $comment)
   {{ $comment->text }}
   <a href="#">Reply</a>
@endforeach
</div>

在返回视图本身时,将返回 $comments 数组。

基本上,如果有一种方法可以将$comment-&gt;id 附加到将使用 Laravel Blade 或 AlpineJS 单击Submit 按钮时发送到服务器的数据,但不会在&lt;script&gt; 标记之间创建任何附加功能,我很感兴趣?我的意思是,是否可以这样做:&lt;a href="#" @click.prevent="formData.append('parent_comment_id', {{ $comment-&gt;id }})"&gt;Reply&lt;/a&gt;

编辑:

我错误地表达了自己。我不想每次单击Reply 时都附加新的id,而是要在使用$comment-&gt;id 的@987654331 单击Submit 按钮时覆盖将要发送到服务器的数据中的相应属性@ 被点击了。

【问题讨论】:

    标签: laravel alpine.js


    【解决方案1】:

    我假设您使用的是Laravel Resource Controller

    不确定我是否完全理解您为什么要在提交表单时发送所有评论 ID,但在调用路由 post.store 时最好发送帖子 ID

    <form action="{{ route('post.store', ['post' => $post]) }}" method="POST">
    

    如果您想获得所有评论 id 并在模型中设置正确的 model relationships,您可以在控制器中获得所有 cmets 的帖子。

    要在表单中发送特定 ID,请创建一个新的 &lt;input name="comment_id" value=""&gt; 并填充该字段。

    【讨论】:

    • 不不,我只想发送一个$comment id,也就是点击了Reply 的那个。我的意思是,我可以使用&lt;input&gt;,我可以隐藏它并设置它的值,点击Reply,否则将其设置为0,但有没有更清洁的方法?
    • 好吧,input 就这样
    猜你喜欢
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多