print("<tr onclick='ajax_post({$result["date"]}, {$result["work"]});'>");
并在js函数上抓取变量,如:
ajax_post(a, b){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create variables to send to our PHP file
var url = "ajaxform.php";
var dt = a;
var wk = b;
var vars = "date="+dt+"&workout="+wk;
}
但这不起作用。这是我的代码:
<script>
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create variables to send to our PHP file
var url = "ajaxform.php";
var dt = document.getElementById("date").value;
var wk = document.getElementById("work").value;
var vars = "date="+dt+"&workout="+wk;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
<p id="status"></p>
<div>
<table class="table table-striped">
<thead>
<tr>
<th class="bold">Date</th>
<th class="bold">Work</th>
<th class="bold">Mood</th>
</tr>
</thead>
<tbody>
<?php
foreach ($results as $result)
{
print("<tr onclick='ajax_post();'>");
print("<td class='date' id='date' name='date' value='{$result["date"]}'>{$result["date"]}</td>");
print("<td id='workout' name='workout' value='{$result["work"]}'>{$result["work"]}</td>");
print("<td>{$result["mood"]}</td>");
print("</tr>");
}
?>
</tbody>
</table>
</div>
非常感谢任何帮助。如果用普通的js做这个是不可行的,我对jquery解决方案开放。
感谢!!!!!!
答案 0 :(得分:1)
我会使用$.ajax()
来简化一些事情。但除此之外,您应该使用classes
而不是ids
来定位元素,因为ids
应该始终是唯一的(只有一个元素应该具有该ID),而任意数量的元素都可以具有相同的元素class
。
当用户点击一行时,在该行中找到您需要的元素并获取其值,然后在ajax调用中发送它们。
以下是一个例子:
$('tr').click(function() {
var row = $(this);
var url = "ajaxform.php";
var dt = row.find(".date").text();
var wk = row.find(".work").text();
var vars = "date=" + dt + "&workout=" + wk;
$.ajax({
type: "POST",
url: url,
data: vars,
success: function(response) {
// handel successs
},
error: function(response) {
// handel error
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<table>
<tr>
<td class="date">1/2/2015</td>
<td class="work">legs</td>
</tr>
<tr>
<td class="date">1/3/2015</td>
<td class="work">arms</td>
</tr>
<tr>
<td class="date">1/4/2015</td>
<td class="work">lats</td>
</tr>
<tr>
<td class="date">1/5/2015</td>
<td class="work">calves</td>
</tr>
<tr>
<td class="date">1/6/2015</td>
<td class="work">quads</td>
</tr>
</table>