首页 > 解决方案 > 如何使用javascript获取url并将其作为变量传递给php

问题描述

我有代码来获取使用 Wordpress 构建的一些数据(术语 = page-a)。
目前,获取page-a的数据'terms' =>'page-a'并在example.com/page-a页面上显示。
我想更改此数据获取代码,以便可以获取沿着较低页面 url 的数据(例如,在 page-b at 上的数据example.com/page-b)。
我创建了一个代码来获取 url$_SERVER并对其进行转换,但我无法获取 url,因为我使用的是 ajax。我想用javascript获取url并将其传递给php。
我应该如何进行更改?

函数.php

add_action('wp_ajax_get_case', 'dk_get_case');
add_action('wp_ajax_nopriv_get_case', 'dk_get_case');
function dk_get_case() {
    $headers['Access-Control-Allow-Origin'] = '*';
    $return = ['status' => false, 'data' => [], 'message' => ''];

    $case_clinics = [1,2,3,4];
    foreach($case_clinics as $key => $case_clinic){
        // (1)Get the current URL
        $http = is_ssl() ? 'https' : 'http' . '://';
        $url = $http . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];         

        // (2)Get a string such as'page-a' from the URL
        $keys = parse_url($url); 
        $path = explode("/", $keys['path']); 
        $terms = $path[2];

        $dk_posts = get_posts(
            array(
                'showposts' => -1,
                'post_type' => 'case',
                'tax_query' => array(
                                    'relation' => 'AND',
                    array(
                        'taxonomy' => 'case_clinic',
                        'field' => 'term_id',
                        'terms' => $case_clinic
                    ),
                                    array(
                        'taxonomy' => 'case_category',
                        'field' => 'slug',
                        'terms' => 'page-a'
                    )
                )
            )
        );

分类-case_category-page-a.php

                    <div class="col case-right">
                        <h3 style="font-family:'Futura PT'; font-weight:600">Clinic</h3>
                        <h4 style="font-weight:600">Clinic</h4>
                                            //data display position
                        <div class="case-img" data-slider-3></div>
                        <div class="popup"></div>
                    </div>

试过了

页脚.php

    <script>
        jQuery(document).ready(function () {
var url = window.location.href;
$.ajax({
    type: "GET",
    url: "taxonomy-case_category-page-a.php",
    data: {"url": url},
});
        });

分类-case_category-page-a.php

<?php var_dump($_GET['url']); ?>

错误

GET: 404error
https://example.com/pagea/taxonomy-case_category-page-a.php?url=https%3A%2F%2Fcharme-beauty.jp%2Fstaging%2Fcase%2Fpagea%2F

标签: javascriptphpajax

解决方案


推荐阅读