通过这种方式,您可以使用ajax传递值,您可以在php脚本中从$\\u POST获取值
jQuery(document).ready(function(){
jQuery(\'.dayLink a\').click(function(){
var li_id = jQuery(this).closest(\'.dayLink\').attr(\'id\');
jQuery.ajax({
url: \'url_to_php_script\',
data: {dayValue: li_id,action:call_to_ajax},
method: \'POST\',
success: function(res){
console.log(res);
}
})
});
});
右括号出现故障。
<?php
if(isset($_GET[\'li_id\'])){
$test = $_GET[\'li_id\'];
echo $test;
}
?>
添加了新的php脚本以响应POST方法传递的值。
下面是php文件中的整个脚本。
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(\'.dayLink a\').click(function(){
var li_id = jQuery(this).closest(\'.dayLink\').attr(\'id\');
jQuery.ajax({
url: \'https://grat-itudefitness/wp-content/themes/divi-child-gratitudefitness/includes/b2p_program_navigation.php\',
data: {dayValue: li_id},
method: \'POST\',
success: function(res){
console.log(res);
}
})
});
});
</script>
<?php
if(isset($_GET[\'li_id\'])){
$test = $_GET[\'li_id\'];
echo $test;
}
?>
<!-- Exercise Menu -->
<ul class="topnav" id="myTopnav">
<li class="dayLink" id="day_1"><a href="javascript:void(0)">Day 1</a></li>
<li class="dayLink" id="day_2"><a href="javascript:void(0)">Day 2</a></li>
<li class="dayLink" id="day_3"><a href="javascript:void(0)">Day 3</a></li>
<li class="dayLink" id="day_4"><a href="javascript:void(0)">Day 4</a></li>
<li class="dayLink" id="day_5"><a href="javascript:void(0)">Day 5</a></li>
<li class="dayLink" id="day_6"><a href="javascript:void(0)">Day 6</a></li>
<li class="dayLink" id="day_7"><a href="javascript:void(0)">Day 7</a></li>
</ul>
您需要的代码::
**要保存在模板文件中的代码**
<?php
$actionName = \'callMyAjax\';
$nonce = wp_create_nonce($actionName);
?>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(\'.dayLink a\').click(function(){
var li_id = jQuery(this).closest(\'.dayLink\').attr(\'id\');
jQuery.ajax({
url: \'https://example.com/wp-admin/admin-ajax.php\',
data: {dayValue: li_id,action:<?php echo $actionName; ?>,ajaxOrigin:<?php echo $nonce; ?>},
method: \'POST\',
success: function(res){
console.log(res);
}
})
});
});
</script>
**保留在函数中的代码**
<?php
function myAjaxHanlder()
{
if(isset($_POST[\'ajaxOrigin\']) && wp_verify_nonce($_POST[\'ajaxOrigin\'], \'callMyAjax\')){
if(isset($_POST[\'li_id\'])){
$test = $_POST[\'li_id\'];
echo $test;
}
}
}
add_action(\'wp_ajax_callMyAjax\', \'myAjaxHanlder\' );
add_action(\'wp_ajax_nopriv_callMyAjax\', \'myAjaxHanlder\' );
?>