我想通过Ajax获取一些数据,但是必须有一些错误,因为结果是空的
脚本:
<script>
function showUser(value) {
var values = $(this).serialize();
$.ajax({
url: "test.php",
data: {
id: value
},
type: "POST",
success: function(data){
$("#result").html(data);
}
})
}
</script>
HTML:
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="result"></div>
test.php的:
<?php
$id = @$_POST['id'];
$pdo = $db->query('SELECT * FROM people WHERE id = "' . $id . '"');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo $row['id'];
}
?>
答案 0 :(得分:1)
<强> HTML: - 强>
<select id ="myselect" name="users" onchange="showUser()">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
<br>
<div id="result"></div>
<强> 使用Javascript: - 强>
<script>
function showUser() {
$.ajax({
url: "test.php",
data: {
id: $( "#myselect option:selected" ).val();
},
type: "POST",
success: function(data){
$("#result").html(data);
}
});
}
</script>
<强> PHP: - 强>
<?php
if(isset($_POST['id'])){
$id = $_POST['id'];
// i don't know from where $db is coming so check yourself
$pdo = $db->query('SELECT * FROM people WHERE id = "'.$id.'" LIMIT 1');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo $row['id'];
}
}else{
echo "Please select value from select box";
}
?>
注意: -
同时阅读prepared statements
并使用它们来阻止SQL Injection
。感谢 强>
答案 1 :(得分:1)
如果您不想使用jquery,可以执行以下操作: -
var http = new XMLHttpRequest();
var url = "****Some URL (php etc to process the sql data)******";
var p = hex_sha512(userPass.value);
var params = "email="+userEmail.value+"&p="+p+"&adminStat=true";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
http.onreadystatechange = function() {
if (http.readyState == 4) {
//Todo
// check addition stat and go to the destination page
if (http.responseText == "success") {
window.location = "*****Destination URL********";
} else {
alert("error");
}
}
};