【问题标题】:Wordpress Jquery MySQL PluginWordpress Jquery MySQL 插件
【发布时间】:2016-09-01 17:06:00
【问题描述】:

所以,我正在开发一个利用 jquery 和 mysql 动态更新下拉框的插件。

当页面第一次加载时,下拉框应该填充从 mysql 中选择的数据。但是,除了渲染到页面的空下拉框之外,没有任何东西可以工作。并且不会发出错误消息。

我在这里俯瞰什么?

插件/myplugin/myplugin.php

<?php

/**
 * Plugin Name: Test
 * Plugin URI: 
 * Description: This plugin performs dynamic region updates into select boxes in WordPress
 * Version: 1.0.0
 * Author: Me
 * Author Email: 
 * License: GPL2
 */

function getregions_scripts() {
  wp_enqueue_script(
    'getregions-script',
    plugin_dir_url(__FILE__) . "assets/getregions.js",
    array('jquery'),
    '1.0',
    true
  );

  wp_localize_script(
    'getregions-script', // this needs to match the name of our enqueued script
    'gymRegions',      // the name of the object
    array('ajaxurl' => admin_url('admin-ajax.php')) // the property/value
  );
}
add_action( 'wp_enqueue_scripts', 'getregions_scripts' );

add_action( 'wp_ajax_showcountries', 'showcountries_callback' );
add_action( 'wp_ajax_no_priv_showcountries', 'showcountries_callback' );
function showcountries_callback() {

  include_once("pdo_mysql.php");

  pdo_connect("localhost","user","password");
  pdo_select_db("wpdb");


  $action=$_POST["action"];

  if($action=="showcountries"){
     $showcountry = pdo_query("Select country_data from wp_usertable");

     if (!$showcountry) {
         $message  = 'Invalid query: ' . pdo_error() . "\n";
         $message .= 'Whole query: ' . $showcountry;
         die($message);
     }else{
         foreach($showcountry as $row){
            echo '<option value=".$row[country_code].">.$row[country_name].</option>';
         }
     }
  }
  else if($action=="showregions"){
      $country_id= $_POST["country_id"];

      $showregion = pdo_query("Select region_code, region_name from regiontbl
                WHERE country_id=?", pdo_real_escape_string($country_id));

      if (!$showregion) {
          $message  = 'Invalid query: ' . pdo_error() . "\n";
          $message .= 'Whole query: ' . $regionquery;
          die($message);
      }else{
         foreach($showregion as $row){
            echo '<option value=".$row[region_code].">.$row[region_name].</option>';
         }
      }
  }

}

function showcountries_frontend() {
$the_html = '
<form id="MyForm">
        <div style="float: left">
            <select id="CountryList" onchange="getRegion()" size="20"></select>
            <select id="RegionList" size="20" onchange="getMap()"></select>
        </div>
        <div id="cityList" style="float: right"></div>
</form>';
return $the_html;
}
add_shortcode("sc_frontend", "showcountries_frontend");

?>

plugins/myplugin/assets/getregions.js

function initialize($) {
    .......
    feedData($);
}

jQuery(document).ready(function ($) { initialize($); });

function feedData($) {
    jQuery(document).ready(function ($) {
        var serialized = $('#MyForm').serialize();
        $.ajax({
            cache: false,
            type: "POST",
            async: false,
            url: "gymRegions.ajaxurl",
            data:{action=showcountries, serialized},
            success: function (data) {
                $('#CountryList').append(data);
            },
            error: function (data, status, error) {
                console.log(data);
                console.log(status);
                console.log(error);
            }
        });
    });
}

【问题讨论】:

  • 您的数据是否从您的 ajax 调用中返回?在success 之后尝试console.log(data) 并告诉我们。
  • @jbrya029 不,没有什么可以恢复。我在success:中放置了一个console.log(data),但没有生成任何输出。有什么想法吗?
  • 您的问题可能与您的 pdo 连接、您的“action”后置变量或您的 echo 语句引发错误有关。您是否尝试过在 Chrome 的开发者工具 --> 网络选项卡中查看 XHR 请求?如果你抛出一个 PHP 错误,它应该出现在这里,而它可能不会在 ajax 调用中返回为“数据”。
  • @jbrya029 我在 Chrome 中查看了 XHR 请求,同样,那里也没有生成任何内容。我只在开发人员工具中收到“无效的速记属性初始化程序”错误通知 --> 来源。
  • 尝试将else 语句添加到您的$action if/elseif 以回显错误消息。如果您仍然一无所获,您可能只需要回显文件的每一步,直到找到断点并从那里解决问题。

标签: javascript php jquery mysql wordpress


【解决方案1】:

这里有很多事情需要解决。

您的 ajax 调用正在寻找一个位置来进行调用;但是,您正在传递此值:

url: "gymRegions.ajaxurl",

因此,生成的 404 基于该字符串:192.168.0.50/index.php/testing-2/gymRegions.ajaxurl

本地化脚本

为了将插件目录的位置传递给 javascript 文件,您需要本地化脚本。这可以在 wordpress 中使用以下方法完成:

wp_enqueue_( 'getregions-script', plugin_dir_url(__FILE__) . "assets/getregions.js", array('jquery'), '1.0', true);
wp_localize_script( 'getregions-script', 'gymRegions', array('ajaxurl' => plugin_dir_url(__FILE__) . 'assets/getregions-ajax.php'));

这将允许您在 ajax 调用中不带引号调用 gymRegions.ajaxurl。

制作你的 ajax 文件

现在这已经完成了,你可以在你的插件中创建一个新的 php 文件:assets/getregions-ajax.php。该文件将包含您当前的 showcountries_callback 函数内容(不需要是函数)。此页面上的任何内容都将被执行。

为了包含 wp,我通常使用这样的东西:

header('Content-Type:application/json');
header("X-Robots-Tag: noindex, nofollow", true);

/* find and load wp to avoid duplicating class */
if (file_exists('../../../../wp-load.php')) :
    require_once('../../../../wp-load.php');
else:
    require_once('../../../../../wp-load.php');
endif;

在此之后,我将要求我的课程或执行任何代码。

JSON 编码输出

最后,考虑对您的输出进行 JSON 编码。无需立即回显所有内容,而是在文件末尾创建一个 $html 变量:

echo json_encode($html, JSON_PRETTY_PRINT);

一步一个脚印

一开始这可能有点令人困惑,但一步一步地做会有所帮助。不要试图一口气吃完所有东西,只需专注于让 'hello world' 从您的 ajax 调用返回,然后从那里构建。

可能还有其他问题,但这至少应该让您走上正确的道路。

【讨论】:

【解决方案2】:

删除 console.log 那么数据将不会被获取

【讨论】:

  • 您能详细说明您的意思吗?我删除了整个错误:函数部分,但这没有任何区别。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-14
  • 1970-01-01
  • 2013-12-16
  • 2015-01-26
  • 2011-06-18
相关资源
最近更新 更多