使用AJAX和PHP中的POST更新查询中的多个Div

时间:2016-03-01 17:27:00

标签: php jquery html sql-server ajax

尝试使用AJAX PHP和HTML更新多个Div。以下是附加示例。我可以更新一个DIV,但是我希望从PHP SELECT语句返回多个结果并在每个DIV中返回每个列 基于列名选择,如:

 $("#IDBox").html(msg.ID);

 $("#FirstNameBox").html(msg.FirstName);

这可能吗?设计将是用户输入ID和帖子,它们执行PHP Query,返回每个DIV的值,即ID,名字,姓氏等。 谢谢伙计们!

<?php  
$databaseName = "SQL_SERVER" ;
$serverName = "192.168.89.89";   
$uid = "Rep02";     
$pwd = "Password123";     


$connectionInfo = array( "UID"=>$uid,                              
                         "PWD"=>$pwd ,                              
                         "Database"=>$databaseName);   


/* Connect using SQL Server Authentication. */    
$conn = sqlsrv_connect( $serverName , $connectionInfo); 


$action = $_POST['action'];

$tsql = "SELECT [ID], [FirstName]
  FROM TABLE1 
  WHERE [Player_ID] = '$action'";

/* Execute the query. */    

$stmt = sqlsrv_query( $conn, $tsql);  


    //Working Query
/* Iterate through the result set printing a row of data upon each iteration.    BR=."\n" */

  while($row = sqlsrv_fetch_ARRAY($stmt, SQLSRV_FETCH_ASSOC)){
      { 
    echo $row['ID'];
    echo $row['FirstName'];


    }}  

/* Free statement and connection resources. */    
sqlsrv_free_stmt( $stmt);    
sqlsrv_close( $conn);    

?>

<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Winner</title>
        <style type="text/css">
            #IDBox, #FirstNameBox {
                width: 100px;
                height: 18px;
                border: 1px solid #999;
            }

        </style>

<script src="../MS/Jquery/jquery-1.11.0.min.js"></script>



<script>        


            function myCall4() {
            var Player_Card = $('#Player_Card').val();

    $.ajax({ url: 'DBv6.php',
 data: {action:Player_Card},
 dataType: 'html',
 type: 'post',
 success: function(msg) {

           $("#IDBox").html(msg);   
            $("#FirstNameBox").html(msg);   

}
})

};


</script>




    </head>


    <body>

    ID:
    <div  id="IDBox"> </div>

    First Name:
    <div  id="FirstNameBox"> </div>

    <br>

    <form>
            <tr>
        <td style="width: 100px;">Player Card:</td>
        <td style="width: 150px;"><input type= "text" ID= "Player_Card" placeholder= "Please Swipe Card..." ></td>

            </tr>


            <td><input type = "button" value="Submit" onclick = "myCall4();">  

    </form>





    </body>
</html>

1 个答案:

答案 0 :(得分:1)

是的,当然有可能,使用echo json_encode($row);

以JSON而不是简单的字符串返回你的ajax

并检索对象中的ajax成功返回,然后您就可以轻松地单独检索它。

$.ajax({
  dataType: "json",
  data: {action:Player_Card},
  type: 'post',
  url: "DBv6.php",
  success: function(msg) {
    alert(msg.FirstName); //use your statement instead
    alert(msg.ID); //use your statement instead
  }
});