我试图编写的函数是用户在框中输入一个ID整数,JS读取该框并使用JSON和Ajax将该数据发送到PHP文件。 此文件将接收ID并运行MySQL查询并将该答案返回到变量中以发送回JavaScript并放入表中。 我不知道如何让PHP变量发送回JavaScript或它返回的格式,任何帮助将不胜感激。
$("#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 :(得分: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