2 回答

TA貢獻(xiàn)1735條經(jīng)驗(yàn) 獲得超5個(gè)贊
是的,Ajax是解決此問題的方法,這是使用Ajax的代碼版本:
形式:
<?php
lineChartAll_Generate();
echo "<form id="my-form">
Select Date Range:
<input type='date' name='date1'>
<input type='date' name='date2'>
<button id='submit'> submit </button>
</form>";
?>
JavaScript / jQuery:
單擊提交按鈕,jQuery會(huì)將表單數(shù)據(jù)收集到一個(gè)數(shù)組中并將其存儲(chǔ)在formData變量中,然后使用的名稱將其提交給PHP并使用的名稱dataForPHP觸發(fā)ajax操作鉤子your_custom_action
jQuery('#submit').on('click', function() {
let formData = jQuery('#my-form').serializeArray(); // retrieves the form's data as an array
jQuery.ajax({
url: ajaxurl, // default ajax url of wordpress
type: 'POST',
data: {
action: 'your_custom_action', // use this action to handle the event
dataForPHP: formData // this is your form's data that is going to be submitted to PHP by the name of dataForPHP
},
success: function( response ) {
// do what you want with the response echoed from PHP
},
error: function( error ) {
// show an oops! message
}
});
});
});
PHP:
PHP使用jQuery觸發(fā)的ajax操作來運(yùn)行一個(gè)函數(shù),因此,這add_action('wp_ajax_your_custom_action', 'your_custom_function');意味著當(dāng)your_custom_action觸發(fā)時(shí),運(yùn)行your_custom_function。
add_action('wp_ajax_your_custom_action', 'your_custom_function'); // ajax actions in wordpress must have the prefex 'wp_ajax_'
function your_custom_function() {
if ( isset( $_POST['dataForPHP'] ) ) {
// do staffs with submitted data from the html form...
}
echo 'what you want to receive as a response in jQuery.ajax() success function'; // ignore this line if you don't want to receive any response.
}
- 2 回答
- 0 關(guān)注
- 306 瀏覽
添加回答
舉報(bào)