2017-07-25 99 views
0

我被困在我试图从PHP文件中的数据读取到JSON格式的脚本的一部分的值的表。我新的PHP只是想从W3Schools的学习,我被困在HTTP POST方法将数据发送到PHP文件,并显示在HTML,但我得到一个错误使基于一个下拉菜单

Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse() at XMLHttpRequest.xmlhttp.onreadystatechange

这里是我的代码我做了迄今为止在前面部分我用HTML和JavaScript为:

<script> 
 
function change_myselect(sel) { 
 
    var obj, dbParam, xmlhttp, myObj, x, txt = ""; 
 
    obj = { "table":sel, "limit":20 }; 
 
    dbParam = JSON.stringify(obj); 
 
    xmlhttp = new XMLHttpRequest(); 
 
    xmlhttp.onreadystatechange = function() { 
 
    if (this.readyState == 4 && this.status == 200) { 
 
     myObj = JSON.parse(this.responseText); 
 
     txt += "<table border='1'>" 
 
     for (x in myObj) { 
 
     txt += "<tr><td>" + myObj[x].name + "</td></tr>"; 
 
     } 
 
     txt += "</table>"   
 
     document.getElementById("demo").innerHTML = txt; 
 
    } 
 
    }; 
 
    xmlhttp.open("POST", "get_email.php", true); 
 
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
 
    xmlhttp.send("x=" + dbParam); 
 
} 
 
</script>
<select id="get_email" name="get_email" onchange="change_myselect(this.value)"> 
 
<option value="">Choose an option:</option> 
 
<option value="3">Customers</option> 
 
<option value="4">Products</option> 
 
<option value="5">Suppliers</option> 
 
</select> 
 

 

 
<p id="demo"></p>

这里是我的PHP文件:

<?php 
    include("admin/include/config.php"); 
    $id=$_POST['get_email'] 
    if(isset($_POST['$id'])){ 
    $sql=mysql_query("select * from subscription where id=".$id); 

    $returnArray = array(); 
    while ($row=mysql_fetch_array($sql)){ 
    $returnArray = 
    array("email"=>$row['email'],"creationDate"=>$row['creationDate']); 
    } 

    // return JSON response. 
    header('Content-Type: application/json'); 
     echo json_encode($returnArray); 
     } 

你能告诉我我在做什么错误在上面的脚本。由于提前

+0

也许尝试改变'MyObj中= JSON.parse(this.responseText);''到= MyObj中JSON.parse(xmlhttp.responseText);' –

+0

@AntonisTsimourtos也更新它之后,我仍然得到了同样的错误 –

+0

你有一个错误的JSON格式。我觉得应该是'OBJ = { “表”: “选择”, “极限”:20 }' - 加' “”''左右其sel'是一个字符串。 –

回答

0

你在PHP代码已经有些错误,你只是打印电子邮件。这不是JSON字符串。

阅读更多地了解JSON:​​

通过阅读你从对象访问名称的JS代码,所以可能需要改变PHP脚本如下,

<?php 
    include("admin/include/config.php"); 
    $id=$_POST['get_email'] 
    if(isset($_POST['$id'])){ 
    $sql=mysql_query("select * from subscription where id=".$id); // You missed semi colon here. 

    $returnArray = array(); 
    while ($row=mysql_fetch_array($sql)){ 
    $returnArray = array("email"=>$row['email'],"name"=>$row['name']); // assuming column name exists.  
} 

// return JSON response. 
header('Content-Type: application/json'); 
echo json_encode($returnArray); 
} 
+0

是现在我已经打印JSON格式的数据,但还是同样的问题 –

+0

我只是想才达到这样的事情,但是从我的数据库https://www.w3schools.com/js/tryit.asp?filename=tryjson_html_table_dynamic –

+0

什么你得到的错误是? –

相关问题