【问题标题】:Use JSON string from AJAX request in PHP [closed]在 PHP 中使用来自 AJAX 请求的 JSON 字符串 [关闭]
【发布时间】:2021-12-17 01:15:36
【问题描述】:

以下内容让我一无所知...

使用 AJAX,我通过一个外部 PHP 文件从我的数据库中请求了一些数据,该文件返回一个 JSON 字符串。我想将返回的 JSON 字符串转换为 PHP 变量(数组),以便我可以再次在页面上回显我的数组索引。它可能不会那样工作,但这是我在这里尝试做的......如何再次在 PHP 中使用返回的 JSON?

开启index.php,用户选择触发AJAX请求的单选按钮(也在同一页面上):

$(document).ready(function() {
  $("input[name='select']").click(function() {
    var select = $("input[name='select']:checked").val();
    $.ajax({
      type: "POST",
      url: "processing_file.php",
      data: { select: select },
      cache: false,
      success: function(data) {

        // WHAT DO I DO HERE INSTEAD OF alert(data); ???

      },
      error: function(xhr, status, error) {
        console.error(xhr);
      }
    });
  });
});

请求由processing_file.php处理其中包含一个用于处理AJAX请求的类。(该类扩展了具有所有凭据和查询处理的数据库类它,它工作正常。)

class Ajax extends Database {

  public function getInfo() {
    
    $id = $_POST['select'];

    $query = "SELECT * FROM table WHERE table.id = '$id';";
    
    $data = $this->execute($query);
    $info = $data[0];

    $json = json_encode($info);

    echo $json;
    /* I don't want to echo it, I need this variable on index.php */

  }

} # End class

$ajax = new Ajax;
$ajax->getInfo();

返回index.php,AJAX 请求开始并返回的地方,我想将返回的 JSON 字符串转换为 PHP 变量(数组)。所以我可以在需要显示的地方回显我的数组数据。这是其余的 index.php 看起来像:

<form class="form" action="process_form.php" method="POST">
  <div class="tab">

      <?php
        // Loop through results of earlier query
        foreach ($post_data as $post) {
      ?>
      
        <!-- The PHP echo results come from an earlier (irrelevant) database query
          It creates a group of radio buttons, which the user selects to trigger AJAX
        -->
        <label class="pselect-container"> <?php echo $post['name']; ?>
          <input type="radio" name="select" value="<?php echo $post['id']; ?>">
          <span class="pselect-checkmark" style="width:100%;">
            <?php echo $post['name']; ?>
          </span>
        </label>

      <?php
        }
      ?>
      
  </div>
  <div class="tab">
    Tab 2:

    <!-- The PHP echo results below should come from the AJAX request
      My idea was to convert the returned JSON to a PHP array, so I can
      echo the array data here.
    -->
    The first piece of data I want to show is <?php echo $info[0]; ?> </br>
    <div style="width:100%;"> But there is also more: <?php echo $info[1]; ?> </div>
    <p>And finally, for <?php echo $info[2]; ?> another paragraph element.</p>

  </div>

  <div class="tab">
    Tab 3:
    <!-- Might want to show more AJAX result data here -->
  </div>
  <div class="tab">
    Tab 4:
    <!-- Might want to show more AJAX result data here -->
  </div>
</form>

为了这个问题,我尝试使用 &lt;?php echo $info[index]; ?&gt; 回显 JSON 数据。我知道它不是那样工作的,但它澄清了我在这里想要完成的事情。如果我可以将我的 JSON 数据转换为 PHP 数组,我会这样做。

请注意:出于隐私原因,我更改了一些变量和名称,并简化了我的数据库查询。

【问题讨论】:

  • 啊,请注意:出于隐私原因,我更改了一些变量和名称,并简化了我的数据库查询。 我认为您可能在简化方面迈出了一步
  • 尝试$json = json_encode(['answer'=&gt;$info]);,然后在javascript中该值将可用于data.answer中的Javascript(不是PHP)另外添加dataType: "json",到您的ajax参数以确保
  • @ADyson 评论相应调整:)
  • 如果您向我们展示您希望在索引页面的 HTML 中的哪个位置添加输出,将会有所帮助。
  • 我已经编辑了我的问题以进一步澄清它,并添加了我想要在index.php 上显示 JSON 数据的 HTML。为了我的问题,我目前正在尝试回显返回的 JSON。我知道它不会那样工作,但它澄清了我在这里尝试做的事情。

标签: php jquery json ajax


【解决方案1】:

如果您在另一个后端脚本中需要此变量,您应该使用另一个 ajax 将它传递给那里。

但是如果你做一个 ajax 来获取 json 然后将它传递给另一个脚本,为什么不在你的第一个 ajax 调用中做呢?做这样的事情:

$(document).ready(function() {
  $("input[name='select']").click(function() {
    var select = $("input[name='select']:checked").val();
    $.ajax({
      type: "POST",
      url: "processing_file.php" // do whole work here not in index.php,
      data: { select: select },
      cache: false,
      success: function(data) {
    
      },
      error: function(xhr, status, error) {
        console.error(xhr);
      }
    });
  });
});

【讨论】:

  • 我认为 OP 对需求的解释很糟糕,我认为他们希望在 Ajax 调用的成功方法中访问 PHP 数据。不是我的反对
  • hmm,所以他们应该做 JSON.parse,或者向 ajax 参数提供 dataType: "json",并像使用 js 对象一样使用它:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多