【问题标题】:Function doesn't echo variable函数不回显变量
【发布时间】:2022-01-25 15:21:52
【问题描述】:

我目前正在学习基本的 php 和 jQuery。

我创建了在鼠标悬停时获取 url 的脚本,并将其发送到 php。

问题是,如果我想将此数据传递给 php 变量,它似乎不起作用,因为它只回显“'这是我们的 JS 变量:'”

脚本:

<script type="text/javascript">
    
var hrefValue;

jQuery(document).ready(function($) {
    $('#bio-box').find('a').mouseover(function() {
        hrefValue = ($(this).attr('href'))
       console.log(hrefValue)
    });
    $.ajax({
        url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
        data: {
            'action': 'php_tutorial',
            'php_test': hrefValue
        },
        success: function(data){
            console.log("happy")
        }
    });
}); 

</script>

functions.php:

function our_tutorial(){
        if(isset($_REQUEST)){
            $testing = $_REQUEST['php_test'];
    
            echo 'This is our JS Variable :'.$testing;
    
            global $wpdb;
            $wpdb->insert(
                $wpdb->prefix.'lms_enroll',
                [
                    'ID' => $testing
                ]
            );
        }
        die();
    }
    add_action('wp_ajax_php_tutorial', 'our_tutorial');

【问题讨论】:

标签: php ajax wordpress echo


【解决方案1】:

问题是 - 当页面加载时,变量的值为空。所以解决方案是在鼠标悬停的那一刻调用ajax。

 var hrefValue;

jQuery(document).ready(function($) {
    $('#bio-box').find('a').mouseover(function() {
        hrefValue = ($(this).attr('href'))
        //console.log(hrefValue)
        $.ajax({
            url: frontendajax.ajaxurl,
            type: 'POST', 
            data: {
                'action': 'image',
                'php_test': hrefValue
            },
            success: function(data){
                $('#featured-image').html(data);
                //console.log(data);
            }
        });
    });
}); 

【讨论】:

    【解决方案2】:

    解决方案:

      $.ajax({
            url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
            type: 'post', // define type
            data: {
                'action': 'php_tutorial',
                'php_test': hrefValue
            },
            success: function(data){
                console.log("happy")
            }
        });
    
    
    functions.php:
    // post to et value
    $test = $_POST['php_test'];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      相关资源
      最近更新 更多