1 回答

TA貢獻1817條經驗 獲得超6個贊
這更像是一個建議的替代方案,而不是一個答案。
會話變量的使用在其他情況下會更有用,例如我們可以混淆 ID 值或在孤立(斷開連接)導航級別中重用它......
但在這種情況下,我最好只使用一個表單并使用 Ajax 填充它的輸入值。
此演示僅更新 postId' 32 的值......當它與獲取 Id 并返回它的 jSon 對象的功能性動態 ajax 處理程序一起使用時,它應該可以工作。
$('.post__editBtn').click(function() {
var myform = $('.post__edit');
var postId=$(this).attr('data-id');
myform.find("input[name='post__editHidden']" ).val(postId);
$.ajax({
type: "GET",
dataType: "json",
url: "https://api.myjson.com/bins/kx5xs", // replace with php later
data: {id: postId},
success: function(data) {
myform.find("input[name='postTitle']" ).val(data[0].title);
myform.find("textarea[name='postMsg']" ).val(data[0].content);
},
error : function(){
alert('Some error...!');
}
});
$('.post__edit').fadeIn();
//for demo puropose to show the new value in the update form:
console.log($(".post__edit input[name='post__editHidden']").val());
});
.post__edit{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class"post">
Post 30<button type="button" data-id="30" class="post__editBtn">Edit post</button>
</div>
<div class"post">
Post 32<button type="button" data-id="32" class="post__editBtn">Edit post</button>
</div>
<div class"post">
Post 37 <button type="button" data-id="37" class="post__editBtn">Edit post</button>
</div>
<!--all data-id values would be replaced with '.$postID.' in the php loop-->
<form method="post" action="../../php/includes/updatePost.php" class="post__edit">
<input type="text" name="postTitle" placeholder="Edit title" required>
<textarea name="postMsg" maxlength="255" placeholder="Edit message" required></textarea>
<button type="submit">Save Post</button>
<button class="post__edit-close">Close</button>
<input type="hidden" name="post__editHidden" value="">
</form>
然后我們添加一個文件 ex:ajax.php,我們用 ajax 調用它,我們在其中獲得一個 ID,我們確實從數據庫中獲取該記錄以返回我們的 json。像這樣的東西:
<?php
$id=$_GET['id'];
$stmt = $conn->query("SELECT title,content * FROM posts WHERE postId=$id LIMIT 1");
$result=...
echo json_encode($result);
要獲得這樣的json:
{"id": "32","title": "POst 32","content": "POst 32 talks about HiTECH"}
- 1 回答
- 0 關注
- 110 瀏覽
添加回答
舉報