2017-04-23 54 views
0

我试图代码的功能是一个用户输入ID整数成箱中,JS读取盒和使用JSON和Ajax该数据发送到PHP文件。 该文件将在ID和运行MySQL查询并返回该回答到一个变量被送回JavaScript和投入的表。 我被困在如何让PHP变量发送回JavaScript或它返回的格式,任何帮助将不胜感激。发送与MySQL数据PHP变量回到JavaScript和AJAX

$("#sid").click(function() { 
    var selectID = document.getElementById("selectedID").value;//selects the ID it wants to 
    var jsonSID = {"ID":selectID}; 
    var jsonSelectID = JSON.stringify(jsonSID); 


    if(selectID=='') 
     alert("Please select an ID to find"); 
    else{ 
     alert("goes to ajax") 
     $.ajax ({ 
      type:"POST", 
      url:"viewData.php", 
      data: {selectData: jsonSelectID}, 
      dataType: 'json', 
      success: function(data){ 

       console.log(data.id); 
       console.log(data.name); 
      }, 
      error: function(e){ 
       alert("Didn't work, refresh and it should work"); 
      } 

     }); 
    } 

}); 

PHP文件

  <?php 
    $link = mysqli_connect("localhost", "root", "", "assignment5"); 
    if($link === false){ 
     die("ERROR: Could not connect. " . mysqli_connect_error()); 
    } 
      $json = $_POST['selectData']; //Takes in the selected ID array 
      $data = json_decode($json); //decodes the selected ID JSON array 
      $selectedID = $data->ID; // this is the user selected ID 

      $query = "SELECT * FROM datadump WHERE id = '$selectedID'"; //You don't need a ; like you do in SQL 
      $result = mysql_query($query); 
       $array = mysql_fetch_row($result); 
       echo json_encode($array); 
    ?> 
+0

分裂前端可粘贴的console.log的'输出(数据);' –

+1

什么是或不是发生了什么? *“我卡住了”*没有告诉我们任何有意义的东西。另外如果没有$结果呢?它总是最容易写出完美的作品的一部分......它是走的时候其他意外事件的放在一起 – charlietfl

+0

它不返回任何信息,而给我约一个错误意想不到的“<”或只是返回什么都没有。 – MrShedford

回答

0

注:MySQL的ID弃用更好地切换到库MySQLi或PDO

如果你想访问一个或两个变量的变量,你可以孙中山数组,并可以像这样回顾:

success: function(data id){ 
    alert(data); 
    alert(id); 
}, 

如果要检索多个记录,你需要这样的 : 有从获取你的PHP错误应该是这样的:

$query = "SELECT * FROM datadump WHERE id = '$selectedID'"; 
    $result = mysql_query($query); 

    while($res = =mysql_fetch_array($result)){ 
    $data[] = $res; 
    } 
$res['data'] = $data; 
echo json_encode($res); 

即发送JSON对象后,并在您需要$.each function