【问题标题】:Retrieving data from a variable through http request通过 http 请求从变量中检索数据
【发布时间】:2017-06-07 03:50:03
【问题描述】:

我是 http 请求和 php 的新手。我有一个http:

xmlhttp.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200) {
         var doc = xmlhttp.response;
         myFunc(doc);
       }
   };
   xmlhttp.open("GET",some.php",true);
   xmlhttp.responseType = "document";
   xmlhttp.send(null);

php文件:

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body id="idk">
        <?php
        include("include1.inc");
        include_once("include2.inc");

        $cxn = mysqli_connect($host,$user,$passwd,$dbname) or die("Could not connect to the server at this time.");
        $table = 'table';

        $data = retrieveData($table, $cxn);//selects data from mysql db return array
        var_dump($data);

         ?>
      </body>
    </html>

如何从数据库中获取保存数组的数据变量? 当我转储或打印变量时,数组被传递给`responseText。有没有更雄辩的方法来抓住那个数组?

【问题讨论】:

  • 字体颜色表示您忘记了引号。
  • xmlhttp.open("GET",some.php",true); => xmlhttp.open("GET","some.php",true);

标签: javascript php ajax xmlhttprequest


【解决方案1】:

您将响应类型设置为“文档”,因此您将获得 HTMLDocument onbject 作为响应。因此,如果您只需要获取数据变量,请尝试以这种方式更改您的代码: javascript:

   xmlhttp.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200) {
         var doc = xmlhttp.response;
         myFunc(doc);
       }
   };
   xmlhttp.open("GET","some.php",true);
   xmlhttp.responseType = "json";
   xmlhttp.send();

还有 php:

<?php
        include("include1.inc");
        include_once("include2.inc");

        $cxn = mysqli_connect($host,$user,$passwd,$dbname) or die("Could not connect to the server at this time.");
        $table = 'table';

        $data = retrieveData($table, $cxn);//selects data from mysql db return array
        echo json_encode($data);
?>

请注意,在这种情况下,php 脚本不包含任何 html 标记,仅包含 php 代码。

【讨论】:

  • 这很好用@user1722564。这会将我的 $data 变量转换为 json 对象,以允许我对其进行操作并从中检索信息。
猜你喜欢
  • 2019-04-04
  • 2019-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-12
相关资源
最近更新 更多