【问题标题】:Uncaught reference error when trying to create basic wordpress ajax plugin尝试创建基本 wordpress ajax 插件时未捕获的参考错误
【发布时间】:2020-08-23 00:39:46
【问题描述】:

我有一个自定义的 Wordpress 插件。我遇到了一个错误:“er=1:12 Uncaught ReferenceError: at_thm_ajax_obj is not defined at HTMLInputElement”。我不确定是否需要添加到 wp-admin/ajax.php 文件或其他地方。

目录文件夹是wp-content/plugins/'at-thm-medicarelookup',这里是函数文件'at-thm-medicarelookup.php':

<?php
/*
 *
 * Plugin Name: Medicare Member ID Lookup
 * Description: Custom plugin for Medicare Member ID Lookup
 * Version: 1.0.0
 * Author: Adrian Townsend
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

// First register resources with init
header("Access-Control-Allow-Origin: *");

add_action('wp_enqueue_scripts', 'at_thm_medicarelookup_resource');
function at_thm_medicarelookup_resource() {
  wp_enqueue_script('at-thm-medicarelookup-script', plugins_url('js/at-thm-medicarelookupscript.js', __FILE__), array('jquery'), 1.0, true);
  wp_enqueue_style('at-thm-medicarelookup-style', plugins_url('css/at-thm-medicarelookupstyle.css', __FILE__), array(), "1.0", "all");

  wp_localize_script('ajax-script', 'at_thm_ajax_obj', array(
    'ajax_url' => admin_url( 'admin-ajax.php' ),
    'nonce' => wp_create_nonce('at_thm_nonce'),
  ));
}

function at_thm_medicarelookupajax() {
  $response = 'Found it';
  echo wp_json_encode( $response );
  wp_die();
}
add_action('wp_ajax_at_thm_medicarelookup', 'at_thm_medicarelookupajax');
add_action('wp_ajax_nopriv_at_thm_medicarelookup', 'at_thm_medicarelookupajax');

这是 jquery 文件:


jQuery(document).ready(function($){

  $('#thm_member-verify').click(function(){
  console.log('clicked');
  $.ajax({
    type: 'POST',
    _ajax_nonce: at_thm_ajax_obj.nonce,
    dataType: 'json',
    url: at_thm_ajax_obj.ajax_url,
    data: {
      action:  "at_thm_medicarelookupajax",
      memberId: document.getElementById('input_25_10_6').value
    },
    success: function(data, status, xhr){
      console.log(data);
    }
  });
});

});

【问题讨论】:

    标签: jquery ajax wordpress plugins


    【解决方案1】:

    发现我的错误。 wp_localize_script 的正确方法...wp_localize_script('at-thm-medicarelookup-script', 'at_thm_ajax_obj', array(...));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-09
      • 2017-08-31
      • 2016-10-03
      • 2020-08-31
      • 1970-01-01
      • 2019-01-20
      • 2017-01-02
      相关资源
      最近更新 更多