所以我需要声明我在 php 中用 ajax 传递的值,因为当我使用例如 if(!empty($_POST["fsearch"]))
时它什么也没显示,当我放$fsearch=$_POST['fsearch'];
时,它给了我未定义的索引错误。我在jquery中有变量search_term,它将值传递给php中的"fsearch"(这也是我的输入字段的名称)。我不知道如何声明这个从Jquery到PHP的值。有代码:
jQuery(document).ready(function ($) {
$("#food_search").keyup(function(event){
var search_term =$(this).val();
console.log(search_term);
$.ajax({
type:"POST",
url:"/Food-Search",
data:{fsearch:search_term},
success:function(res){
$("#food_search_result").html(res);
console.log(res);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!----------------------------------------------------------------
HTML
----------------------------------------------------------------->
<form method="POST">
<p>Търсене на храни: <input type="text" name="fsearch" id="food_search"></p>
</form>
<!----------------------------------------------------------------
PHP
----------------------------------------------------------------->
<?php
if(!empty($_POST["fsearch"])) {
echo "True";
} else {
echo "False";
}
?>
所以我需要将"fsearch"定义为来自jquery的值。并检查名称为"fsearch"的输入字段是否为空。感谢您的所有建议!
尝试这样做。
jQuery(document).ready(function ($) {
$("#food_search").on('blur',function(){ //blur event ...triggres when input field is unfoused
var search_term =$(this).val();
console.log(search_term);
$.ajax({
type:"POST",
url:"/Food-Search.php",//if you are not using .htaccess or routing give file name with .php extension
data:{fsearch:search_term},
success:function(res){
$("#food_search_result").html(res);
console.log(res);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
});
});