[英]Send hidden input data using AJAX
I am using AJAX live search plugin. 我正在使用AJAX实时搜索插件。
It passes input data to backend-search.php
它将输入数据传递到backend-search.php
backend-search.php
selects data from the database and return to the search page. backend-search.php
从数据库中选择数据并返回搜索页面。
Now I want to pass one hidden input value with the search query. 现在,我想通过搜索查询传递一个隐藏的输入值。
Hidden Input 隐藏的输入
<input type="hidden" name="group" value="<?php echo $grp_id; ?>" />
Following is my html in search.php
以下是我在search.php
html
<div class="search-box"> <input type="text" autocomplete="off" placeholder="Search..." /> <div class="result"></div>
Javascript 使用Javascript
<script type="text/javascript"> $(document).ready(function(){ $('.search-box input[type="text"]').on("keyup input", function(){ /* Get input value on change */ var term = $(this).val(); var resultDropdown = $(this).siblings(".result"); if(term.length){ $.get("backend-search.php", {query: term}).done(function(data){ // Display the returned data in browser resultDropdown.html(data); }); } else{ resultDropdown.empty(); } }); // Set search input value on click of result item $(document).on("click", ".result p", function(){ $(this).parents(".search-box").find('input[type="text"]').val($(this).text()); $(this).parent(".result").empty(); }); }); </script>
How do I send the data of the hidden input field with above js? 如何使用上述js发送隐藏输入字段的数据?
You could use $.post
instead of $.get
like this: 您可以这样使用$.post
而不是$.get
:
$.post( "backend-search.php?query="+ term, { hidden_key: "hidden_value"})
.done(function(data) {
alert( "Data Loaded: " + data );
});
So, customizing it for your code, 因此,根据您的代码对其进行自定义,
if(term.length) {
// get value of hidden field
var hidden_value = $('[name="group"]').value();
// make a post request, but also pass query params
$.post("backend-search.php?query=" + term, { group: hidden_value})
.done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
}
Here, everything after the ?
在这里,之后的一切?
mark is passed as a query string (ie via get method) whereas the hidden field is passed by the Post method. 标记作为查询字符串(即通过get方法)传递,而隐藏字段由Post方法传递。 In your Php script, use print_r($_REQUEST)
to verify that you get the 2 parameters as desired. 在您的Php脚本中,使用print_r($_REQUEST)
验证您是否根据需要获得了2个参数。
Also, you should encode URI parameters like this encodeURIComponent(term)
to make sure your javascript does not break if the user enters special characters 另外,您应该对URI参数进行编码,例如此encodeURIComponent(term)
,以确保如果用户输入特殊字符,则您的JavaScript不会中断
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.