在PHP变量中获取Ajax脚本响应
我有三个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:
?> $.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); } }); }); <?php $ajaxResponse = ????
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']; } }
那么如何在main.php中获取$ajaxResponse = ????
ajax响应值$ajaxResponse = ????
?
您可以创建要显示响应内容的div
在你的情况下,它是在标签之后
并使用innerHTML来显示内容
使用此代码
如果它有用,请告诉我
你不能这样使用它。
为什么:
javascript / jQuery是一种脚本语言,当DOM完全加载并且元素可用于制作选择器时,它在浏览器中运行。
虽然php是在页面加载之前在服务器方式上运行的服务器端语言。
因此,简而言之,您无法为php变量分配ajax响应。
有一件事你可以做一个隐藏的输入并将响应值放入其中,你可以获得该值来使用它。
success:function(data){ alert(data); $('#hiddenInputId').val(data); // set the response data to the hidden input and use it. }
这是答案:
使用以下方式在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();