我需要一种简单的方法来将多个PHP变量检索到html div中。我搜索了很多帖子,但我找不到答案。
我正在寻找类似的东西:
去到的index.php
<?php
$name = 'Jonh';
$phone = '123456789';
$details = 'Detail about';
?>
的index.php
<div class="name">Your Name is : <?php echo $name; ?></div>
<div class="phone">Your Phone Number is : <?php echo $phone; ?></div>
<div class="details">Your Details are : <?php echo $details; ?></div>
我想通过AJAX Call来获取它们而不是echo。
执行此操作的正确AJAX REQUEST语法是什么?
更新
我的坏我以前没有注意到,但忘了说我还需要逐个加载电话。我的请求太多,需要花费很多时间。
请问查询.each()函数应该像我想要的那样工作吗?
答案 0 :(得分:1)
在你的PHP中:
<?php
echo json_encode(Array(
'name' => "John",
'phone' => "1234567890",
'details' => "Details about..."
));
您的HTML:
<div class="name">Your Name is : <span class="name_value"></span></div>
<div class="phone">Your Phone Number is : <span class="phone_value"></span></div>
<div class="details">Your Details are : <span class="details_value"></span></div>
你的jQuery:
$(document).ready(function(){
$.getJSON('user-info.php',function(data){
$(".name_value").html(data.name);
$(".phone_value").html(data.phone);
$(".details_value").html(data.details);
});
});
注意:您将user-info.php
字符串设置为抓取用户信息的PHP脚本的URL(相对或绝对值)。
答案 1 :(得分:0)
您需要一个PHP脚本来输出包含您想要的值的JSON,并且您需要一个Javascript处理程序来询问该数据并在获取该数据时执行某些操作。这是一个例子:
# File: go-to-index.php
<?php
$name = 'Jonh';
$phone = '123456789';
$details = 'Detail about';
echo json_encode(
[
'name' => $name,
'phone' => $phone,
'details' => $details
]
);
然后是你的HTML页面:
<!-- File: index.php -->
<div class="name">Your Name is : <span class="container"></span></div>
<div class="phone">Your Phone Number is : <span class="container"></span></div>
<div class="details">Your Details are : <span class="container"></span></div>
<button class="loadMe" type="button">Click here to make things work</button>
最后你的jQuery:
$(document).ready(function() {
$('.loadMe').click(function() {
$.ajax({
// Path to your backend handler script
url: 'go-to-index.php';
// Tell jQuery that you expect JSON response
dataType: 'json',
// Define what should happen once the data is received
success: function (result) {
$('.name .container').html(result.name);
$('.phone .container').html(result.phone);
$('.details .container').html(result.details);
},
// Handle errors in retrieving the data
error: function (result) {
alert('Your AJAX request didn\'t work. Debug time!');
}
});
});
});
你可以在任何事件上做到这一点 - 按钮只是一个例子。您也可以使用普通的Javascript或任何其他库,只需使用jQuery,因为您在问题中标记了它。