如何通过ajax将mysql结果作为jSON传递

时间:2015-05-06 09:30:43

标签: php jquery mysql ajax json

我不确定如何通过ajax JSON将mysql查询的结果传递到html页面。 ajax2.php

$statement = $pdo - > prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement - > execute(array(':key2' => $key2, ':postcode2' => $postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while ($row = $statement - > fetch()) {
    echo $row['Name']; //How to show this in the html page?
    echo $row['PostUUID']; //How to show this in the html page?
    $row2[] = $row;
}
echo json_encode($row2);

如何通过下面的ajax传递上面的查询结果显示在html页面中?

我的ajax

$("form").on("submit", function () {
    var data = {
        "action": "test"
    };

    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "ajax2.php", //Relative or absolute path to response.php file
        data: data,
        success: function (data) {
            //how to retrieve the php mysql result here?
            console.log(data); // this shows nothing in console,I wonder why?
        }
    });
    return false;

});

5 个答案:

答案 0 :(得分:3)

您的json编码应该是这样的:

 $json = array();
 while( $row = $statement->fetch()) {
     array_push($json, array($row['Name'], $row['PostUUID']));
 }

    header('Content-Type: application/json');
    echo json_encode($json);

在你的javascript部分,你不必做任何事情来取回你的数据,它存储在成功函数的数据var中。 您只需显示它并在网页上随意执行任何操作

答案 1 :(得分:0)

在ajax success函数中,您可以使用JSON.parse(data)来显示JSON数据。

以下是一个例子:

Parse JSON in JavaScript?

答案 2 :(得分:0)

header('Content-Type: application/json');
$row2 = array();
$result = array();
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
   // $row = $statement->fetchAll(PDO::FETCH_ASSOC);
     while( $row = $statement->fetch())
     {
         echo $row['Name'];//How to show this in the html page?
          echo $row['PostUUID'];//How to show this in the html page?
          $row2[]=$row;
     }
if(!empty($row2)){
$result['type'] = "success";
$result['data'] = $row2;
}else{
$result['type'] = "error";
$result['data'] = "No result found";
}
echo json_encode($row2);

并在您的脚本中:

$("form").on("submit",function() {

    var data = {
      "action": "test"
    };
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
      type: "POST",
      dataType: "json",
      url: "ajax2.php", //Relative or absolute path to response.php file
      data: data,
      success: function(data) {
        console.log(data);
         if(data.type == "success"){
           for(var i=0;i<data.data.length;i++){
              //// and here you can get your values //
             var db_data = data.data[i];
              console.log("name -- >" +db_data.Name );
              console.log("name -- >" +db_data.PostUUID);
           }
         }
         if(data.type == "error"){
            alert(data.data);
         }
      }
    });
    return false;

});

答案 3 :(得分:0)

您可以将json编码的字符串保存到数组中,然后将其值传递给javascript。

参考下面的代码。

<?php 
// your PHP code 
$jsonData = json_encode($row2); ?>

您的JavaScript代码

var data = '<?php echo $jsonData; ?>';

现在data变量包含所有JSON数据,现在您可以继续使用您的代码,只需删除以下行

 data = $(this).serialize() + "&" + $.param(data);

不需要它,因为data变量是字符串。

ajax2.php文件中,您可以通过

获取此信息
json_decode($_REQUEST['data'])

答案 4 :(得分:0)

我会...... ..

<div class="rowtitle">
  <ul>
    <li style="display: inline;">
      <div class="service-wrapper1">
        <a href="#">
          <div class="wrappername">menu 1</div>
        </a>

      </div>
    </li>
    <li style="display: inline;">
      <div class="service-wrapper1">
        <a href="#">
          <div class="wrappername">menu 2</div>
        </a>

      </div>
    </li>
    <li style="display: inline;">
      <div class="service-wrapper1">
        <a href="#">
          <div class="wrappername">menu 3</div>
        </a>

      </div>
    </li>
  </ul>
</div>

然后在javascript方面:

$rows = $statement->fetchAll(FETCH_ASSOC);
header("content-type: application/json");
echo json_encode($rows);

(不要依赖网页浏览器为你解析它。响应因为应用程序/ json标头,它在浏览器之间有所不同......用responseText手动完成);