2016-08-05 33 views
0

我是一名初学者,我试图回显数组并将它们追加到我创建的html分支中。我所做的AJAX电话很成功,但答复没有出现在我分配给它的分部内。经过进一步检查,我发现我收到的回复数组长度超过600(我期待10条记录)。所以我的回声PHP文件或者HTML文件的接收端一定有些问题,但是却无法弄清楚它是什么。Javascript,PHP,AJAX:如何回显数组并将它们追加到html分区中

这里是我的代码:

listdiscount.php

<?php 
header("Access-Control-Allow-Origin: *"); 
header("Content-Type: application/json; charset=UTF-8"); 

$conn = new mysqli("localhost", "root", "root", "bencoolen"); 

$userid = $_GET['userid']; 

$result = $conn->query("select userid, codename from discountcode where userid ='" . $userid . "' "); 

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ 
    printf("Userid: %s '' Codename: %s", $row["userid"], $row["codename"]); 
} 

$conn->close(); 
?> 

的index.html(与JS代码)

<html> 
<script> 
    function mydiscount(){ 
          var userid = "jimmy"; 
          var xmlhttp = new XMLHttpRequest(); 
          var url = serverURL() + "/listdiscount.php"; 
          url += "?userid=" + userid; 
          alert(url); 
          xmlhttp.onreadystatechange=function() { 
           if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
            alert("readystate=4 and status =200"); 
            mydiscountresult(xmlhttp.responseText); 
           } 
           } 
           xmlhttp.open("GET", url, true); 
           xmlhttp.send(); 
         } 

         function mydiscountresult(response) { 
          var arr = response; 
          alert(arr);   //alerted 
          alert(arr.length); //alerted 600+ arrays 
          alert("mydiscountresult working"); //alerted 
          var i; 
          $("#discountcontent").empty(); 
          for(i = 0; i < arr.length; i++) { 
          $("#discountcontent").append("<b>" + arr[i].userid + "</b>"+ arr[i].codename + "<hr>"); 
          } 
         } 

         mydiscount(); 
</script> 

        <div data-role="content" class="ui-content" id="discount"> 
        LIST OF DISCOUNT CODE:<br> 
        <div id="discountcontent" class="ui-grid-solo"> 
        </div> 
        </div> 
</html> 

这里是我的回应是什么惊动时,如:

补充说明:我的php文件位于不同的文件夹中,所以serverurl()被声明和使用 这里。

+0

看来,应对缺什么? – technico

+0

尝试控制/提醒arr [i] .userid等的值,并检查控制台是否有错误报告。 –

+0

确定我会在几分钟内提醒阵列用户ID!也加入了反应,我忘了! –

回答

0

获取请求返回一个json数组,因此您需要使用json解析将其转换为正常数组。你可以请更改代码行为

mydiscountresult(JSON.parse(xmlhttp.responseText)); 

它会正常工作。

0

功能xmlhttp.responseText retun a 字符串,对不对?

您将此字符串转换为函数mydiscountresult并将其复制到变量var中。它仍然是字符串,不是吗?

所以提醒做工精细,并在那里做的工作在字符串(长度600等)

然后你走在这个逐个字母(这是你的for循环是做什么的)。在每封信var[i]上,您都会尝试阅读userid。我认为没有一个普通的信件(calld char)有一个名为userid的房产。所以这导致一个空字符串。我想你想从字符串xmlhttp.responseText获得数组。为此,你只要让JSON解析这个字符串,它给了你一个对象

JSON.parse(xmlhttp.responseText)

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

相关问题