调用异步请求加载信息

时间:2015-09-11 22:33:35

标签: javascript php jquery ajax wordpress

在我的wordpress主题中,我使用api来加载电影信息。所以,我试图调用jquery函数,它将执行ajax请求并将结果加载到预定义的DIV中。

但是当我在content.php页面中调用该函数时,document.ready尚未完成。所以,要么我需要在document.ready()之外定义jquery函数(我认为这不是一个好主意),或者我需要在bodyOnload上调用该函数。在后一种情况下,我不确定如何在页面内容中包含使用wordpress的get_the_content()函数解析的URL。

任何人都可以提供建议。

PHP(content.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
    }
});

使用下面的functions.php

添加custom.js
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');

2 个答案:

答案 0 :(得分:1)

您遇到了范围问题。您在另一个函数中声明了该函数,这意味着在添加脚本时,它不会在全局范围内可见。您需要移动从全局范围内的其他脚本调用的函数。

AJAX调用仍然可以放在ready事件中,所以它会在DOM准备好后加载脚本。

答案 1 :(得分:0)

就像减号4所述,这是一个时间问题。您正在调用仅在dom ready上创建的函数。解决方法是在dom上调用ajax函数,然后在脚本的前面输出你需要的变量(你调用ajax函数)

即。 content.php

    $urls = preg_split($pattern, $subject); // Let say I have all the links in this variable
    echo '<script> var urls='.json_encode($urls).';</script>'; 

注意你所做的就是在这里定义网址,这是不好的标记,但它需要在这里,因为你正在使用需要在wp循环中运行的the_content()

在你的js文件中

    function loadMovies(urls){
        console.log(urls);
        // define our function.
    }

    jQuery(document).ready(function () {

        loadMovies(urls){
            console.log(urls);
            // call our predefined function
        }
    });

你仍然可以在你的document.ready函数中定义你的函数,但是它更干净,可以创建函数,然后在其他函数中调用(在上面是一个anon函数的情况下)