【发布时间】:2017-11-16 18:06:32
【问题描述】:
我正在尝试从我的数据库中检索数据,然后将其显示为模式,但是,当我在 ajax 中添加 dataType:"json" 时,它似乎不再执行我的 php 文件。我是 ajax 新手和 json 所以我真的不知道我在哪里遇到问题。顺便说一句,我正在尝试实现 CRUD 功能,这就是我尝试将数据加载到模式中进行更新的原因。我使用相同的模式进行创建和更新。
这是我的 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 字符串.. -
您需要将数据库中的数据编码为 json。使用
echo json_encode($row); -
@ImClarky 我的错,我的代码上实际上有
echo json_encode($row);,我不小心删除了它 -
谢谢@Devon 我会检查的