【发布时间】:2015-09-11 22:33:34
【问题描述】:
在我的 wordpress 主题中,我使用 api 加载电影信息。因此,我正在尝试调用 jquery 函数,该函数将执行 ajax 请求并将结果加载到预定义的 DIV 中。
但当我在 content.php 页面中调用该函数时,document.ready 尚未完成。所以,要么我需要在 document.ready() 之外定义 jquery 函数(我认为这不是一个好主意),要么我需要在 bodyOnload 上调用该函数。在后一种情况下,我不确定如何从页面内容中包含使用 wordpress 的 get_the_content() 函数解析的 url。
谁能给点建议。
PHP(内容.php):
$pattern = '/REGEX/i';
$replacement = '$1';
$subject = get_the_content();
$urls = preg_split($pattern, $subject); // Let say I have all the links in this variable
echo '<script>loadMovies('.json_encode($urls).');</script>'; // loadMovies() is not available at this point
现在 loadMovies() 在 custom.js 中定义,如下所示
jQuery(document).ready(function () {
"use strict";
function loadMovies(urls){
console.log(urls);
// HERE I HAVE MY AJAX CALLS WHICH IS NOT AN ISSUE
// THE MAIN ISSUE IS THE FUNCTION IS NOT AVAILABLE AT THE POINT I CALL IT
}
});
custom.js 使用下面的 functions.php 添加
function test_call_js(){
wp_enqueue_script(
'custom-js',
get_stylesheet_directory_uri() . '/js/custom.js',
array( 'jquery' )
);
}
add_action('wp_enqueue_scripts', 'test_call_js');
【问题讨论】:
-
为什么不能在页面末尾(即脚本加载后)运行函数?
-
问题是,这个页面使用了一个特殊的模板,比如说card-view.php。在这个模板文件中,我调用 content.php(使用 get_template_part('content');),它定义了正文部分。所以,如果我在 card-view.php 的末尾调用 loadMovies,由于某种原因,变量 $urls 不可用。 (与 PHP 不同,如果我在 card-view.php 中包含 content.php,我可以访问前者的所有变量)。
标签: javascript php jquery ajax wordpress