繁体   English   中英

检索要在Perl中使用的Javascript变量

[英]Retrieving Javascript Variable to use in Perl

我有这样的html表:

<table class="notices-table" width="100%" cellpadding="0" cellspacing="0" border="0">
       <% foreach my $notice (@regular_posts) { %>
       <form method = "post" id = "post-form-<%= $notice->notice_id()%>">
       <tr class = "click-post" href = "<%= $notice->link() %>">
            <td><b>Date Posted: </b> <%= '' . (split(/\./, $notice->created()))[0] %><br/>
            <b>Title: </b><%= $notice->title() %><br/><br/>
            <%= $notice->content() %>
            </td>
            <td><button class = "archive-button" id="archive-button">Archive</button></td>
       </tr>
       <input type="hidden" id="action" name="action" value="archive" />
       </form>
       <% } %>
</table>

然后我有一个javascript代码,当每个试图检索“ notice_id”的按钮都被按下“归档”按钮时,就会触发该代码:

$(document).ready(function() {
$('button.archive-button').bind('click', function() {
    var id = $(this).attr('id');
    var parts = id.split(/-/);
    var notice_id = parts[2];
    var post_form_id = '#post-form-' + notice_id; 

    $(post_form_id).submit();

    var path_name = window.location.pathname;
    $.ajax(path_name, {
        type: 'POST'
        data: {
            'notice_id2' : notice_id
        },
        success: function(data) {
            console.log('/takeNotice called successfully:');
            console.log(data);
        },
        error: function(jqXHR, textStatus, err) {
            console.error('/takeNotice call failed:');
            console.error(err);
        }
    });

    return false;
});

});

我想将“ notice_id”传递到Perl脚本中,该脚本将使用id从数据库中检索正确的帖子,以便对其进行存档:

my $cgi = CGI->new;
my $notice_id = $cgi->param("notice_id2");
my $form = $Request->Params();
my $notice;
eval {
    $notice = Taskman::Notice->new(notice_id => $notice_id);
};

我对Perl和Javascript / Ajax还是很陌生,所以在这里可能会有更多问题。 任何见识都会很棒。 谢谢

编辑我已经对我的代码做了一些修改。 Ajax似乎正在工作,但是我无法确定我是否仍在正确调用它。 这些脚本在同一页面上。 我仍在检索错误的“ notice_id”

您的方法从根本上没有错,但是您没有正确调用$.ajax ,这将阻止任何工作。

具体来说,您没有为Perl脚本提供URL。 为了举例说明,我假设您的Perl脚本位于/takeNotice路径中(聪明,不是吗?)。 您可以这样称呼它:

$.ajax('/takeNotice', {
    type: 'POST',
    data: {
        notice_id2 : notice_id
    },
    success: function(data) {
        console.log('/takeNotice called successfully:');
        console.log(data);
    },
    error: function(jqXHR, textStatus, err) {
        console.error('/takeNotice call failed:');
        console.error(err);
    }
});

successerror功能不是严格必需的,但是包括它们是一个好主意,当然,当您学习时,它确实有助于理解前端逻辑的流程。

说到这,您可能还应该在此代码中添加一些错误处理:

var parts = id.split(/-/);
var notice_id = parts[2];
var post_form_id = '#post-form-' + notice_id; 

如果该ID的格式不符合您的预期格式,则您最终会得到post_form_id"#post-form-undefined 。这里有些错误处理和控制台日志记录将非常有用。

最后,此行不执行任何操作:

$(post_form_id '#action').val('archive');

如果要设置该值,则需要第二个参数。 如果您试图获取该值,则可能应该将其分配给某些东西。

暂无
暂无

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

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