我試圖從數據庫中檢索數據,然後將其顯示爲模式,但是,當我在ajax中添加dataType:「json」時,它看起來像它不再執行我的PHP文件。我對ajax和json很陌生,所以我不知道我在哪裏遇到問題。順便說一句,我想實現一個CRUD函數,這就是爲什麼我試圖將數據加載到模型進行更新。我正在使用相同的模式來創建和更新。在Ajax中添加dataType:「json」將不起作用
這是我的HTML代碼。
<div class="modal fade" id="addmodal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3>Add Product</h3>
</div>
<div class="modal-body">
<form class="" action="add.php" method="post" id="insert_form" enctype="multipart/form-data">
<div class="form-group input-width center-block">
<input class="form-control" type="file" name="img" id="img" value="" required/>
</div>
<div class="form-group input-width center-block">
<label>Product Name:</label>
<input class="form-control" type="text" name="pnametb" id="pnametb" placeholder="Product Name" required>
</div>
<div class="form-group input-width center-block">
<label>Price:</label>
<input class="form-control" type="text" name="pricetb" id="pricetb" placeholder="Price" required>
</div>
<div class="form-group input-width center-block">
<label>Category:</label>
<select style="" class="action form-control" name="category" id="category" required>
<option value="" disabled selected>Select a category:</option>
<?php
while($row = mysqli_fetch_assoc($result))
{
?>
<!-- Separated HTML and PHP -->
<option value="<?php echo $row['category']?>"><?php echo $row['category']?></option>
<?php
}
?>
</select>
</div>
<div class="form-group input-width center-block">
<label>Description:</label>
</div>
<div class="form-group input-width center-block">
<textarea style="color:black" name="destb" id="destb" class="message-box" placeholder="Description" rows="5" id="comment" required></textarea>
</div>
<input type="hidden" name="id" id="id">
<input class="btn btn-success" type="submit" name="add" value="Add" id="add">
</form>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="button" name="button" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
我的Ajax代碼:
$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
alert(id);
$.ajax({
url:"fetch.php",
method:"post",
data:{id:id},
dataType: "json",
success:function(data){
$('#img').val(data.img);
$('#pnametb').val(data.productname);
$('#pricetb').val(data.price);
$('#category').val(data.category);
$('#destb').val(data.description);
$('#id').val(data.id);
$('#add').val("Edit");
$('#addmodal').modal('show');
}
});
});
這裏是我的PHP文件。
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "testing");
if(isset($_POST["id"]))
{
$query = "SELECT * FROM productsa WHERE id = '".$_POST["id"]."'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_array($result);
echo json_encode($row);
}
?>
告訴我,如果我需要澄清更多的事情,我不是很擅長表達我想要發生的事情。任何幫助將不勝感激。
因爲'$ row'不是JSON字符串.. – Devon
您需要將數據從數據庫編碼到json中。使用'echo json_encode($ row);' – ImClarky
[在php中回顯JSON數據]的可能的重複(https://stackoverflow.com/questions/38183302/echoing-json-data-in-php) – Devon