【发布时间】:2017-08-31 23:34:12
【问题描述】:
你好,我正在寻求帮助
我正在学习如何使用 Ajax 和 PHP,我想做的是在 PHP 中运行查询并将结果存储在 JSON 中。
然后我想echo JSON 并将它的值设置到文本字段中。
这可能吗?
由于我对 Ajax 和 jQuery 还很陌生,我不知道该怎么做。
我试图这样做,但我只得到数组的第一个值。
这是我的代码:
<input type="text" id="text1">
<button type="button" class="btn btn-success" id="send">Success Button</button>
<input type="text" id="text2">
<input type="text" id="text3">
<input type="text" id="text4">
<script type="text/javascript">
$(document).ready(function(){
$("#send").click(function(event){
event.preventDefault();
var Rfc=$("#text1").val();
$.ajax({
type: 'POST',
url: 'search.php',
data: 'Rfc='+Rfc,
dataType : 'json',
success: function(msg){
var datashow = JSON.parse(msg);
$("#text2").val(msg[0].id_person); ///this is the only value that i get
$("#text3").val([1].person_name); ///i want to get the person's name here
$("#text4").val([2].person_address);///i want to get the person's address here
},
error : function () {
alert("error");
}
});
});
});
</script>
这是我的 PHP 文件:
<?php
$rfc=$_POST['Rfc'];
$connection = mysqli_connect("localhost","root","","transferorders");
$query = mysqli_query($connection,"SELECT * FROM person where rfc_number ='$rfc'");
$Data = array();
while($row = mysqli_fetch_assoc($query)){
$Data[]=$row;
echo json_encode($Data);
}
?>
这是我在控制台中得到的
未捕获的类型错误:无法读取未定义的属性“person_name” 在 Object.success(测试 ajax1.php:40)
【问题讨论】:
-
首先,我建议您正确缩进您的代码,这将有助于您和其他审查您的代码的人的可读性。您可能还想检查您的代码并确保所有标签都已关闭(例如,
</html>缺失)。还有一些<script>标签应该放在<head>或<body>部分中,但它们却位于不知名的地方。 -
msg[0].person_name ?
-
我会先看看一些基本的 HTML 标记问题...在尝试弄乱脚本循环之前。
-
1)
<script>标签必须在<head>或<body>内。 2) 您是否正在加载两个引导程序版本? 3)你应该echo返回数组之后 PHP循环结束了。 -
Console.log 在成功回调中使用
console.log(JSON.stringify(msg));记录您的结果...只是看看您得到了什么结果。
标签: php jquery html mysql ajax