[英]How to pass a value from input-text through Jquery Ajax to php function while I type? Wordpress
我正在使用Wordpress,這是我的html代碼:
<input class="form-control text-right" name="majorhead" required="" type="number" id="majorhead"/>
<div class="result_majorhead"></div>
JS代碼:
<script>
jQuery("#majorhead").on("keyup",function(){
jQuery.get(ajaxurl,{'action': 'majorhead'},
function (msg) { jQuery(".result_majorhead").html(msg);
});
});
</script>
這是我在function.php中的代碼
add_action('wp_ajax_nopriv_majorhead', 'majorhead_function');
add_action('wp_ajax_majorhead', 'majorhead_function');
function majorhead_function(){
echo 'hello';
exit();
}
現在,無論我在輸入框中鍵入什么內容,我都可以在同一網頁上顯示一條簡單消息“ Hello”。 現在,我想在鍵入時在顯示消息中顯示輸入文本中的確切值。
例如:如果我鍵入1,則應顯示1,如果我鍵入另一個2,則應顯示12。
您需要在Javascript中執行以下操作:
添加“更改”事件,以便您可以使用箭頭來控制“數字”輸入。
獲取輸入的值。
將值添加到您的GET參數。
jQuery("#majorhead").on("keyup change",function(){ var majorhead_value = $(this).val(); jQuery.get(ajaxurl,{'action': 'majorhead','majorhead_value': majorhead_value}, function (msg) { jQuery(".result_majorhead").html(msg); });
});
在您的PHP腳本中,您應該顯示GET值:
function majorhead_function(){
echo $_GET['majorhead_value'];
exit();
}
如果您有多個輸入,則可以這樣處理它們:
jQuery("#text1, #text2, #text3").on("keyup change",function(){
var majorhead_value = parseInt(0+$("#text1").val());
majorhead_value += parseInt(0+$("#text2").val());
majorhead_value += parseInt(0+$("#text3").val());
jQuery.get(ajaxurl,{'action': 'majorhead','majorhead_value': majorhead_value},
function (msg) { jQuery(".result_majorhead").html(msg);
});
});
我認為您的HTML將如下所示:
<input class="form-control text-right" name="text1" required="" type="number" id="text1"/>
<input class="form-control text-right" name="text2" required="" type="number" id="text2"/>
<input class="form-control text-right" name="text3" required="" type="number" id="text3"/>
<div class="result_majorhead"></div>
HTML代碼
<input class="form-control" placeholder="Search Service" id="search_service" name="service" type="text" autocomplete="off" value="">
這是我在function.php中的Ajax函數
function search_service() {
$search_ser = $_POST['search_ser'];
echo $search_ser;
die();
}
add_action('wp_ajax_search_service', 'search_service');
add_action('wp_ajax_nopriv_search_service', 'search_service');
JS代碼:
jQuery( "#search_service" ).keyup( function() {
var search_ser = jQuery(this).val();
var ajax_url = jQuery('#ajax_url_input').val();
jQuery.ajax({
type:'POST',
url: ajax_url,
data: {
action: 'search_service',
search_ser: search_ser,
},
beforeSend: function(){
},
success:function(data){
jQuery("._services_list").html(data);
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.