通常人們不使用內聯函數,但是使用諸如document.querySelectorAll
之類的方法爲所有行註冊函數,該方法可以從對象/元素的屬性獲取標識。然後,您的函數(openDetails
)將通過ajax發佈到您的後端腳本,該腳本可以在以任何您喜歡的格式返回響應之前執行所需的任何處理。
一些僞代碼來顯示您將採取的流程。你如何處理數據取決於你 - 你可以在屏幕上彈出一個對話框(例如:lightbox樣式),在某處添加一條消息,添加一個新的表格行等等。請注意,ajax函數剛剛寫在這裏,以顯示這個想法,我可以做任何保證,它將所有的工作「是」
html/php
--------
I would include the id in a dataset value like this so that the javascript can get the value when the tr is clicked.
<tr data-id='".$row['id']."'>
javascript
----------
function initialise(){
/* find all table rows and assign a listener function */
var col=document.querySelectorAll('tr');
for(var n in col) if(n && col[n] && col[n].nodeType==1){
col[n].addEventListener('click',openDetails,false);
}
}
function openDetails(event){
/* get the specific id from the table row using it's dataset-id value */
var id=this.dataset.id;
/* pseudo ajax method */
ajax.call(this, '/assets_details.php',{ 'callback':opendetails_callback, 'params':{ 'id':id } });
}
function ajax(url,options){
var req=new XMLHttpRequest();
var params=[];
for(var n in options.params) params.push(n+'='+options.params[n]);
req.onreadystatechange=function(){
if(req.readyState && req.status==200) {
/* invoke callback function with data returned from asset_details.php */
options.callback.call(this, req.response);
}
}
req.open('POST', url, true);
req.send(params.join('&'))
}
function opendetails_callback(response){
/* You would use the callback to create the new content on screen */
alert(response);
}
document.addEventListener('DOMContentLoaded', initialise, false);
後端腳本將監聽發佈的數據,並作出相應的反應。
assets_details.php
------------------
<?php
/* include your functions etc */
if($_SERVER['REQUEST_METHOD']=='POST'){
/* Process your data and send response: example */
echo json_encode($_POST);
}
?>
即便如此,我也沒有()函數定義的openDetails。我不知道如何使用JS將數據發佈到新窗口。 – howdoisysadmin
如果參數是一個整數或某種類型的對象,則不需要引號 - 儘管它是必需的。 – RamRaider