WordPress,jquery加载php文件未找到

我正在通过jquery / ajax将php文件动态加载到Wordpress页面模板中。

我有以下工作在本地服务器上,但当我上传到我的测试网站时,我在加载文件时在控制台中出现404错误。

汇总代码:

var root = location.protocol + '//' + location.host; $(".button-book").click(function(e) { e.preventDefault(); $('#container').load(root+'/wp-content/themes/PL14-Base/inc/bookings-swiss.php'); }); 

你可以在这里看到开发网站。 点击第一个“预订”按钮查看问题。

更新:为了清楚起见,我已经更改了代码以使用确切的URL。直接在浏览器中调用时,可以在正确的URL找到该文件。

这是一个php文件吗? 如果是,请使用get_template_directory_uri(); 帮手

  var root = location.protocol + '//' + location.host; $(".button-book").click(function(e) { e.preventDefault(); $('#container').load('/inc/loaded-file.php'); }); 

我已经设法使用 在加载的php文件的顶部,但这是一个脏修复。 更愿意知道这样做的正确方法。

在您的主插件或函数php或您将执行以下操作的任何地方将全局变量附加到某个脚本

 $main_js_namespace = array( 'ajaxURL' => admin_url('admin-ajax.php'), 'data' => array( 'action' => '', 'method' => '', 'post' => '', ) ); // script handler, javascript global variable name, wp_localize_script('bec_script_handle','gVariable',$main_js_namespace); 

此类类处理ajax调用。

 class ajaxClass { public function __construct() { // ajaxClass can be whatever you want.. add_action('wp_ajax_nopriv_ajaxClass', array($this, 'handle_ajax')); add_action('wp_ajax_ajaxClass', array($this, 'handle_ajax')); } // this simply handle the routing of the functions. public function handle_ajax() { if(isset($_POST['method'])) { $method = $_POST['method']; if(method_exists($this, $method)) { if(isset($_POST['post']) && $_POST['post'] != 'false') { parse_str(stripslashes($_POST['post']), $post); $request = call_user_func(array($this, $method), $post); echo (is_array($request)) ? json_encode($request) : $request; } else { $request = call_user_func(array($this, $method)); echo (is_array($request)) ? json_encode($request) : $request; } } else { $json['success'] = false; $json['msg'] = __CLASS__.'::'.$method.' not found, define first! por favor..'; echo json_encode($json); } } exit; } /* * bla * */ public function someAjaxCall($post){ $toRetun = "whatever Response You Want"; return $toRetun; } } $ajaxClass = new ajaxClass(); 

//这就是我如何调用该脚本

  // the action we chose gVariable.data.action = 'ajaxClass'; // whatever method in the ajax class you want to access gVariable.data.method = 'get_table_schema'; // whatever variable/data you want to pass gVariable.data.post = 'tableName=' + tableName; this functions is a async false and ones done give you an object with the result however any other would work. var getData = function(){ var getData = {}; var setData = function(data) { getData = data; }; return function(){ $.ajax({ url: gVariable.ajaxURL, type: "post", async: false, dataType:'json', data:becGlobal.data, success: function (data) { setData(data); }, error : function (data) { setData(data); } }); return getData; } } getData()();