Ajax没有返回结果
问题描述:
Alright so I have this code which basically finds the user inside the table users and displays it in alert, but it seems that I am doing something wrong. The log shows "Function is not set" and the alert itself displays that.
This is the HTML form I have for it
<center><form method='POST' >
<input id="search_fix" type="text" name="search" placeholder="Search..">
<input type="submit" name="submit_menu_search" style="display: none;">
</form></center>
This is the ajax processing
$(document).ready(function() {
$("#search_fix").keyup(function() {
var search_text = $(this).val();
if(search_text != '') {
$.ajax({
url:"handler.php",
method:"POST",
data:{"function":"search_ajax", search:search_text},
dataType:"text",
success:function(data){
$('#search_result').html(data);
console.log(data);
alert(data);
}
});
}
else {
}
});
});
And these are my PHP functions that I used to basically search for the term
public function search_ajax($term) {
$handler = new sql();
$sql = $handler->connect();
$sql->real_escape_string($term);
$result = $sql->query("SELECT ime FROM users WHERE ime LIKE '%".$term."%'") or die (mysql_error());
if($result->num_rows >= 1){
while($row = $result->fetch_assoc()) {
echo $row['ime'];
}
}
}
if(isset($_POST['function'])) {
switch($_POST['function']) {
case "search_ajax": {
require_once "assembly/user.php";
$user = new User();
$user->search_ajax($_POST['search']);
break;
}
default: {
echo "Unknown AJAX function handler";
break;
}
}
}
else {
echo "Function is not set";
}
答
It sounds like you're using a version of jQuery before 1.9.0. The method:
option didn't exist in the older versions, it was called type:
. That's why you're seeing the parameters appended to the URL, because type: "GET"
is the default.
So change
method: "POST",
to:
type: "POST",
答
try this:
$.ajax({
url:"handler.php",
method:"POST",
data:'{"function":"search_ajax", search:search_text}',
dataType:"text"
})
.done(function(data){
$('#search_result').val(data);
console.log(data);
alert(data);
} ) ;