我無法訪問我在php標籤內創建的文本框值到ajax調用。當我在ajax中打印文本框的值時,會調用它的'undefined',那麼是否有任何方式來訪問文本框的值。看到在代碼中的註釋在管路39如何訪問php標籤內創建的文本框值到ajax調用
<html>
<?php
include 'config.php';
include 'dbconnect.php';
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<table border="1">
<tr>
<th>categoryId</th>
<th>category</th>
<th>Operations</th>
</tr>
<?php
$sql_query = "select category_id,category from cart_category_descriptions limit 10;";
$result = $conn->query($sql_query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<tr id='.$row["category_id"].'><td>'.$row["category_id"].'</td><td><input type=text name="cat" value='.$row["category"].'></td><td><button class="deletedata">Delete</button><button class="updatedata">Update</button></td></tr>';
}
}
else {
echo "0 results";
}
?>
<script>
$(document).on('click','.deletedata',function(){
id = $(this).closest('tr').attr('id'); // Get the clicked id for deletion
alert(id);
$.ajax({
type:'POST',
url:'delete.php',
data:{delete_id:id},
success:function(data){
window.location.reload();
}
})});
$(document).on('click','.updatedata',function(){
id = $(this).closest('tr').attr('id');// Get the clicked id for deletion
alert($("#cat").val());// cannot access, undefined
$.ajax({
type:'POST',
url:'update.php',
data:{update_id:id,
cat: $("#cat").val()},
success:function(data){
alert("updated");
}
})});
</script>
</table>
</html>
根據記錄,在大多數情況下,JavaScript是最好位於