如何使用ajax将php数组索引值传递给html元素

时间:2016-05-07 22:01:19

标签: javascript php ajax

希望这是我对此表格的最后一个问题。我的PHP工作正常,并获得正确的数据。我已经为索引创建了变量,现在想将它们传递给我的js / ajax,因此这些值填充了html文本框。不确定代码是否正确,因为没有很多我在做什么的例子。

我是否在本页的ajax部分正确调用了数组索引?不确定我是否应该使用'innerHTML'或值attribut。如果我要离开,请解释如何做到这一点。如果你需要看我的PHP我可以编辑。谢谢!

 <script type="text/javascript">
function queryStudent() {
    var ajaxRequest;

    try {
        ajaxRequest = new XMLHttpRequest;
    }catch(e) {
        //IE Browsers
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    // Something went wrong
                    alert("Browser not compatible");
                    return false;
                }
            }
    }   


     ajaxRequest.onreadystatechange = function() {
        if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {

            document.getElementById("studentID").value = output1;           
            document.getElementById("stuName").value = output2;
            document.getElementById("email").value = output3;
            document.getElementById("GPA").value = output4;

        }
    };
    var student_ID = document.getElementById('studentID').innerHTML = ajaxRequest.responseText; 

    var queryString = "?studentID=" + student_ID;
    ajaxRequest.open("GET", "search_single.php"+ queryString, true);
    ajaxRequest.send(); //Return value from function 
}
</script>   
<h2>Search for Students by studentID</h2>
<br>
<form name="myForm" action="search_single.php" method="post"> <!--no action or post as it is posted to same page-->
<label>Student ID:</label>
<input type="text" id="studentID">
<br>
<br>
<input type="button" onClick="queryStudent()" value="Search">
<h2>Student information will be displayed in the textboxes below:</h2>
<br>

<table id="outuput">
<tr>
    <td>Student ID:</td>
    <td><input type="text" id="studentID" value="" readonly></td>
</tr>
<tr>
    <td>Student Name:</td>
    <td><input type="text" id="stuName"  value="" readonly></td>
</tr>    
<tr>
    <td>Email:</td>
    <td><input type="text" id="email" value="" readonly></td>
</tr>
<tr>
    <td>GPA:</td>
    <td><input type="text" id="gpa" value="" readonly></td>
</tr>
<br>
</table>
</form>

PHP代码:

if(!isset($studentID)) {
$studentID = filter_input(INPUT_GET, 'studentID', FILTER_VALIDATE_INT);
    if($studentID == NULL || $studentID == FALSE) {
        $studentID = 1;
    }
}
//prepare query 
$query = 'SELECT * FROM student
          WHERE studentID = :studentID';
$statement = $db->prepare($query);
$statement->bindValue(':studentID', $studentID);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);

//var_dump($result); //check indexes

$output = "";
$output1 = $output.$result['studentID'];
$output2 = $output.$result['name'];
$output3 = $output.$result['email'];
$output4 = $output.$result['GPA'];

&GT;

1 个答案:

答案 0 :(得分:2)

您的代码中存在多个错误,例如:

  • id

    的属性
    <input type="text" id="studentID"> 
    

    <td><input type="text" id="studentID" value="" readonly></td>
    

    是一样的。更改其中一个id属性,使其区别开来。

  • 您是以错误的方式从输入字段获取studentID,

    var student_ID = document.getElementById('studentID').innerHTML = ajaxRequest.responseText; 
    

    应该是,

    var student_ID = document.getElementById('studentID').value;
    
  • 服务器端,在PHP代码中

    $output = ""; $output1 = $output.$result['studentID'];... 
    

    您只是将值与空字符串连接并将其分配给另一个变量,顺便说一下,这对您的代码没有任何好处。而是从结果集中获取结果行并使用JLabel API函数对其进行编码。在客户端上,解析此json对象并填充相应的输入字段。

所以你的代码应该是这样的:

<强> HTML:

<h2>Search for Students by studentID</h2>
<br>
<form name="myForm" action="search_single.php" method="post">
    <label>Student ID:</label>
    <input type="text" id="studentID" />
    <br>
    <br>
    <input type="button" onClick="queryStudent()" value="Search">
    <h2>Student information will be displayed in the textboxes below:</h2>
    <br>

    <table id="outuput">
    <tr>
        <td>Student ID:</td>
        <td><input type="text" id="stuID" value="" readonly></td>
    </tr>
    <tr>
        <td>Student Name:</td>
        <td><input type="text" id="stuName"  value="" readonly></td>
    </tr>    
    <tr>
        <td>Email:</td>
        <td><input type="text" id="email" value="" readonly></td>
    </tr>
    <tr>
        <td>GPA:</td>
        <td><input type="text" id="gpa" value="" readonly></td>
    </tr>
    <br>
    </table>
</form>

<强> JavaScript的:

<script type="text/javascript">
    function queryStudent() {
        var ajaxRequest;

        try {
            ajaxRequest = new XMLHttpRequest;
        }catch(e) {
            //IE Browsers
            try {
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                    try{
                        ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e){
                        // Something went wrong
                        alert("Browser not compatible");
                        return false;
                    }
                }
        }   

         ajaxRequest.onreadystatechange = function() {
            if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
                var data = JSON.parse(ajaxRequest.responseText);
                if(data['status']){
                    document.getElementById("stuID").value = data['studentID'];
                    document.getElementById("stuName").value = data['name'];
                    document.getElementById("email").value = data['email'];
                    document.getElementById("gpa").value = data['GPA'];
                }else{
                    alert("You have passed an invalid student ID");
                }
            }
        };

        var student_ID = document.getElementById('studentID').value;
        var queryString = "?studentID=" + student_ID;
        ajaxRequest.open("GET", "search_single.php"+ queryString, true);
        ajaxRequest.send();
    }
</script>   

<强> PHP:

<?php

    if(!isset($studentID)){
        $studentID = filter_input(INPUT_GET, 'studentID', FILTER_VALIDATE_INT);
        if($studentID == NULL || $studentID == false) {
            $studentID = 1;
        }
    }

    // Your PDO connection code

    $result = array(); // To hold the result array
    $query = 'SELECT * FROM student WHERE studentID = :studentID LIMIT 1';
    $statement = $db->prepare($query);
    $statement->bindValue(':studentID', $studentID);
    $statement->execute();
    if($statement->rowCount()){
        $result = $statement->fetch(PDO::FETCH_ASSOC);
        $result['status'] = true;
    }else{
        $result['status'] = false;
    }
    echo json_encode($result);

?>