[英]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);
}
});
success
和error
功能不是嚴格必需的,但是包括它們是一個好主意,當然,當您學習時,它確實有助於理解前端邏輯的流程。
說到這,您可能還應該在此代碼中添加一些錯誤處理:
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.