我试图获得一个发送并收到ajax编码,但我得到一个错误,preco不是Complista2页面中的索引。这是代码:
起始页:
$(function() {
$("#b1").click(function() {
$.ajax({
type: "POST",
url: "complista2.php",
data: $("#preco").val(),
success: $.get("complista2.php", function(data) {
$("#paramount").html(data);
})
});
});
});
<input id="preco" type="text" name="preco" value='250 AND 500'><br><br>
这是Complista2页面:
<?php
$username = "root";
$password = "";
$server = "localhost";
$database = "VRealidade";
$conn = mysqli_connect($server, $username, $password, $database);
if (!$conn) {
die("Erro: " . mysqli_connect_error());
} else {
}
$preco = $_GET['preco'];
$sql = "SELECT * FROM computadores WHERE preco BETWEEN $preco";
$result = mysqli_query($conn, $sql);
echo mysqli_error($conn);
$row = mysqli_fetch_assoc($result);
echo "<div class='entrada'>$row[nome]</div>";
while($row = mysqli_fetch_assoc($result)) {
echo "<div class='entrada'>$row[nome]</div>";
}
?>
编辑:这是表单,但在此代码中没有任何含义。
<form id="pesqmenu2" method='GET'>
<input id="preco" type="text" name="preco" value='250 AND 500'>
</form>
答案 0 :(得分:1)
<?php
$username = "root";
$password = "";
$server = "localhost";
$database = "VRealidade";
$html = "";
//check if preco initialized, and filter for default and special chars as SQL injection ...
if(isset($_POST['preco']) && filter_input(INPUT_POST, 'preco', FILTER_DEFAULT , FILTER_SANITIZE_SPECIAL_CHARS)) {
try {
$preco = $_POST['preco'];
$conn = mysqli_connect($server, $username, $password, $database);
if (mysqli_error()) {
$error = "MySQLi error " . mysqli_error() . ": " . mysqli_error() . "\n<br>When executing:<br>\n$query\n<br>";
exit();
}
$sql = "SELECT * FROM computadores WHERE preco BETWEEN $preco";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$html .= "<div class='entrada'>$row[nome]</div>";
while ($row = mysqli_fetch_assoc($result)) {
$html .= "<div class='entrada'>$row[nome]</div>";
}
//ouput html
header('Content-Type: application/json');
echo json_encode($html);
} catch (Exception $e) {
echo 'Exception reçue : ', $e->getMessage(), "\n";
}
}
您需要更改表单,问题是不要发送到页面.php
<form id="pesqmenu2" name="pesqmenu2" method="post">
<input id="preco" type="text" name="preco" value='250 AND 500'>
<input type="submit" id="b1" name="b1" value="submit"/>
</form>
Ajax改变了:
$(function() {
$.ajax({
method: "POST",
url: "complista2.php",
data: { preco: $("#preco").val() }
})
.done(function( data ) {
$("#paramount").html(data);
});
});
答案 1 :(得分:0)
我找到了解决方案。我所要做的就是在点击事件中添加这个:
$.post("Complista2.php/?preco="+$("#preco").val(), function(data) {
$("#paramount").html(data);
});