我有三个php文件
main.php - to use stored Ajax response.
filter.php - to send Ajax request and get response
insert.php - to store Ajax response for using in main.php
做所有这些事情的主要目的是使用PHP代码使用客户端值,因为服务器和客户端不能相互交换变量值。
响应应存储在main.php
的php变量中。
main.php:
?>
<script>
$.ajax({
type: "POST",
url: "filter.php",
data: { id1: name, id2:"employees"},
success:function(response) {
var res = response;
$.ajax({
type: "POST",
url: "insert.php",
data: { id1: res },
success:function(data){
alert(data);
}
});
});
<script>
<?php
$ajaxResponse = ???? <need to get value of data over here>
filter.php:
// Return employee names
if ($_POST['id1'] == "name" && $_POST['id2'] == "employees") {
$conn = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT " .$_POST['id1']. " FROM 1_employees";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$rows[] = $row['name'];
}
}
echo json_encode($rows);
mysqli_close($conn);
exit (0);
}
insert.php:
if ($_POST) {
if ($_POST['id1'] !== "") {
echo $_POST['id1'];
}
}
那么我怎么能得到ajax响应值在主。php在$ajaxResponse = ????
?
你不能那样用。
原因:
javascript/jQuery是一种脚本语言,当DOM完全加载并且元素可以用来制作选择器时,它运行在浏览器中。
而php是服务器端语言,在页面加载之前运行在服务器上。
简而言之,你不能将ajax响应分配给php变量。
你可以做的一件事是有一个隐藏的输入,把响应值放在里面,你可以得到那个值来使用它
success:function(data){
alert(data);
$('#hiddenInputId').val(data); // set the response data to the hidden input and use it.
}
您可以在想要显示响应内容的地方创建一个div
在你的情况下,它是在<script>
标签
并使用innerHTML显示内容
使用这个代码
<script>
$.ajax({
type: "POST",
url: "filter.php",
data: { id1: name, id2:"employees"},
success:function(response) {
var res = response;
$.ajax({
type: "POST",
url: "insert.php",
data: { id1: res },
success:function(data){
$("#responseContent").html(data);
}
});
});
<script>
<div id="responseContent"></div>
如果有帮助请告诉我
答案如下:
在main.php中使用如下方式获取名称:
-------- filter.php ----------
session_start(); //at the top
$_SESSION['names'] = json_encode($rows);
-------- main.php ----------
session_start();
$issued_to = explode(",", $names);
session_unset();
session_destroy();
答案是简单地使用Javascript将来自Ajax的响应存储到一个隐藏变量中,并利用该变量进行进一步的操作。这解决了我的问题,我相信很多人也会需要这个!