2 回答
![?](http://img1.sycdn.imooc.com/533e4c1500010baf02200220-100-100.jpg)
TA贡献1735条经验 获得超5个赞
是的,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会将表单数据收集到一个数组中并将其存储在formData变量中,然后使用的名称将其提交给PHP并使用的名称dataForPHP触发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触发的ajax操作来运行一个函数,因此,这add_action('wp_ajax_your_custom_action', 'your_custom_function');意味着当your_custom_action触发时,运行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 关注
- 286 浏览
添加回答
举报