请问我的自定义 WordPress 搜索插件有问题。我正在尝试从 JSON 文件进行自动完成

问题描述 投票:0回答:1

除了自动填充功能之外,一切正常

我正在开发一个自定义 WordPress 搜索小部件,其中包括由 AJAX 提供支持的自动填充功能以及从本地 JSON 文件中提取数据。我已经成功设置了基本结构,包括排队脚本和样式、注册小部件块以及定义 AJAX 处理程序。不过,自动填充功能似乎不起作用。这是我的代码:

这是我的自定义搜索widget.php






<?php
/**
 * Plugin Name: Custom Search Widget
 * Description: A custom search widget with autofill for destinations from a local JSON file.
 * Version: 1.0
 * Author: Your Name
 * Text Domain: custom-search-widget
 */

function custom_search_widget_enqueue_resources() {
    wp_enqueue_style('font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css');
    wp_enqueue_style('custom-search-widget-style', plugins_url('/style.css', __FILE__));
    wp_enqueue_script('custom-search-widget-ajax', plugins_url('/ajax.js', __FILE__), array('jquery'), null, true);
    wp_localize_script('custom-search-widget-ajax', 'customSearchWidgetData', array(
        'ajax_url' => admin_url('admin-ajax.php'), // Corrected from 'ajax.js' to 'admin-ajax.php'
        'nonce' => wp_create_nonce('custom_search_nonce'),
    ));
}
add_action('wp_enqueue_scripts', 'custom_search_widget_enqueue_resources');

function custom_search_widget_load_textdomain() {
    load_plugin_textdomain('custom-search-widget', false, basename(dirname(__FILE__)) . '/languages/');
}
add_action('init', 'custom_search_widget_load_textdomain');

function custom_search_widget_register_block() {
    wp_register_script(
        'custom-search-widget-editor',
        plugins_url('block.js', __FILE__),
        array('wp-blocks', 'wp-element', 'wp-components', 'wp-api'),
        filemtime(plugin_dir_path(__FILE__) . 'block.js')
    );

    register_block_type('custom-search-widget/custom-search', array(
        'editor_script' => 'custom-search-widget-editor',
        'render_callback' => 'custom_search_widget_render',
        'attributes' => array(
            'selectedDestination' => array(
                'type' => 'string',
            ),
        ),
    ));
}
add_action('init', 'custom_search_widget_register_block');

function custom_search_widget_render($attributes) {
    $html = '<div class="custom-search-widget">';
    $html .= '<div class="search-container">';
    $html .= '<input type="text" id="destination-search" name="query" placeholder="' . esc_attr__('Enter destination...', 'custom-search-widget') . '" autocomplete="off">';
    $html .= '<i class="search-icon fas fa-search"></i>';
    $html .= '</div>';
    $html .= '<div class="user-status-container">';
    $html .= '<label class="status-checkbox">Active Military<input type="checkbox" name="user_status[]" value="active_military"><span class="checkmark"></span></label>';
    $html .= '<label class="status-checkbox">Veteran<input type="checkbox" name="user_status[]" value="veteran" class="round"><span class="checkmark round"></span></label>';
    $html .= '<label class="status-checkbox">Family Member<input type="checkbox" name="user_status[]" value="family_member"><span class="checkmark"></span></label>';
    $html .= '</div>';
    $html .= '<ul class="search-results-list"></ul>';
    $html .= '</div>';
    return $html;
}
function custom_search_widget_ajax_search() {
    check_ajax_referer('custom_search_nonce', 'nonce');

    $query = sanitize_text_field($_POST['query']);
    $json_path = plugin_dir_path(__FILE__) . 'mydata.json'; // Make sure path is correct

    if (!file_exists($json_path)) {
        wp_send_json_error(['message' => 'JSON file not found.']);
        wp_die();
    }

    $json_data = file_get_contents($json_path);
    $data = json_decode($json_data, true); // Decoding it as an associative array

    if (!$data) {
        wp_send_json_error(['message' => 'Error decoding JSON data.']);
        wp_die();
    }

    // Support either a direct list or nested under a 'Sheet1' key
    $entries = isset($data['Sheet1']) ? $data['Sheet1'] : $data;

    $filtered_data = array_filter($entries, function ($item) use ($query) {
        // Search only by 'City'
        return stripos($item['City'], $query) !== false;
    });

    if (empty($filtered_data)) {
        wp_send_json_error(['message' => 'No results found.']);
    } else {
        wp_send_json_success(['suggestions' => array_values($filtered_data)]);
    }

    wp_die();
}

这是 AJAX.JS 代码

jQuery(document).ready(function($) {
    $('#destination-search').on('input', function() {
        var query = $(this).val();
        if (query.length < 2) {
            $('#search-results-list').empty();
            return;
        }

        $.ajax({
            url: customSearchWidgetData.ajax_url,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'custom_search',
                nonce: customSearchWidgetData.nonce,
                query: query
            },
            success: function(response) {
                var resultList = $('#search-results-list');
                resultList.empty();
                if (response.success && response.suggestions.length) {
                    response.suggestions.forEach(function(suggestion) {
                        resultList.append($('<li>').text(suggestion.City + ' (' + suggestion.Code + ') - ' + suggestion.Country));
                    });
                } else {
                    resultList.append('<li>No results found.</li>');
                }
            },
            error: function(xhr) {
                $('#search-results-list').html('<li>Error processing request: ' + xhr.statusText + '</li>');
            }
        });
    });
});

这是 MYDATA.JSON 文件

{
  "Sheet1": [
    {"City": "New York", "Code": "NY", "Country": "USA"},
    {"City": "Los Angeles", "Code": "LA", "Country": "USA"},
    {"City": "London", "Code": "LDN", "Country": "UK"}
  ]
}


javascript php json wordpress wordpress-plugin-creation
1个回答
0
投票

您的 AJAX 调用可能无法正确触发或处理响应。以下是一些潜在的问题:

元素 ID 不匹配:在 JavaScript 中,您的目标是 $('#search-results-list'),但在 PHP 中,您使用类 search-results-list 生成列表。确保元素定位的一致性。

数据处理:确保正确检索 JSON 数据并且结构符合您的期望。

事件绑定:确保 JavaScript 正确绑定到输入字段。由于您使用的是 jQuery 的 $(document).ready(),所以应该没问题,但请仔细检查浏览器控制台中是否存在冲突或错误。

错误处理:检查浏览器控制台是否有在 AJAX 请求或响应处理期间可能发生的任何 JavaScript 错误。

调试:在 JavaScript 代码中的各个位置插入 console.log() 语句,以查看代码是否按预期执行并检查从服务器接收的数据。

测试:直接测试您的 AJAX 端点(例如,通过使用适当的参数访问 admin-ajax.php)以确保它返回预期的数据格式。

© www.soinside.com 2019 - 2024. All rights reserved.