【发布时间】:2019-03-08 17:10:03
【问题描述】:
我正在创建一个带有插件的 WP Fiche 页面。
此页面的内容需要包含在另一个文件important_file.php 中的许多变量和函数。这就是为什么我将所有内容都放在content_fiche() 函数中并使用require_once('important_file.php')。
问题是我想用 JQuery Ajax 管理我的页面内容的形式并调用文件important_file.php 中包含的函数。
我真的不想修改文件important_file.php,因为我没有编写代码。
<?php
class fiche_content{
private $file_base;
function __construct(){
$this->file_base = plugin_dir_path( dirname( __FILE__ ) ) . 'fiche.php';
$this->init();
}
function init() {
add_action('wp_enqueue_scripts', array($this,'scripts_js'));
add_action('wp_loaded', array($this, 'add_page_fiche'));
}
function scripts_js(){
wp_enqueue_script('fiche_scripts', plugins_url('JS/scripts.js', __FILE__), array('jquery'), '1.0', true);
wp_localize_script('fiche_scripts', 'ajax_object', array('ajaxurl' => admin_url( 'fiche.php' ),
));
}
function add_page_fiche() {
$new_page = array(
'post_title' => wp_strip_all_tags( 'Fiche Projet' ),
'post_content' => $this->content_fiche(),
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page'
);
wp_insert_post( $new_page );
}
function content_fiche(){
require_once ( '.../important_file.php');
$foo = $var_in_important_file;
$html = '<div>'. $foo .'</div>';
$html .= '<form id="form" method="POST">
<input type="hidden" name="build" value="1" />
<input type="submit" name="submit_build" value="Submit" />
</form>';
return $html;
这是我应该管理表单的 JS 文件:
jQuery(document).ready(function($) {
$(document).on('submit', '#form',function(e){
$.post({
url: my_ajax_object.ajax_url,
data: {
data,
'action': 'function_in_important_file'
},
done: function(result) {
}
});
});
});
为了将我的 JS 提交连接到 PHP 函数,我通常只是这样做,但这还不够:
add_action( 'wp_ajax_function_in_important_file', 'function_in_important_file' );
显然,ajax 文件无法访问important_file.php 及其函数。这是我第一次使用 OOP 插件,所以我不知道该怎么做。
【问题讨论】:
-
您是如何设置 Ajax url 端点的?为什么不能在生成 Ajax 响应的代码中包含
important_file?你在使用 WP_Ajax_Repsonse 吗?还是 Rest API? -
我想在我的
content_fiche()函数中使用我的important_file中的一些变量。如果我第二次在 Ajax 响应的内容中包含我的important_file,它将引发错误,因为important_file的函数已经声明。 Ajax URL 端点只是包含该类的 PHP 文件,我编辑了我的帖子。奇怪的是,当我点击表单的提交时,它会删除我的页面。