首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在PHP变量中获取Ajax脚本响应

在PHP变量中获取Ajax脚本响应
EN

Stack Overflow用户
提问于 2015-09-02 16:42:03
回答 3查看 10.6K关注 0票数 0

我有三个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'];

    }

}

那么如何在$ajaxResponse = ????获取main.php格式的ajax响应值呢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-09-02 19:13:18

这就是答案:

使用以下方式获取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();
票数 1
EN

Stack Overflow用户

发布于 2015-09-02 16:48:24

您可以创建一个用于显示响应内容的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>

如果有用,请让我知道。

票数 1
EN

Stack Overflow用户

发布于 2020-07-02 00:16:59

答案是简单地使用Javascript将来自Ajax的响应存储到一个隐藏变量中,并利用该变量进行进一步的操作。这解决了我的问题,我相信很多人也会真正需要它!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32348455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档