【发布时间】:2019-07-13 20:23:00
【问题描述】:
我有一个基于 WP_Query 输出产品的 PHP 文件。
到目前为止一切正常!
但是现在我也想在返回中输出javascript。这不被识别/加载......对我来说,看起来 javascript 不被识别为 javascript。如果我插入警报,这将被忽略。
...
if ( $posts_gf->have_posts() ) :
while ( $posts_gf->have_posts() ) : $posts_gf->the_post();
$response .= '
<script type="text/javascript">
alert("Hello! I am an alert box!");
</script>
<div class="item col-md-4">
Produkt
</div>
';
endwhile;
...
我想从包含在functions.php 中的js 加载轮播。 如果我将轮播的相同代码直接粘贴到模板部分文件“content-glasfaser.php”中,它就可以工作。
这是轮播应加载的文件的摘录(所有 js/css 文件都在加载/存在于页眉和页脚中):
$products = self::$productDefinitions[$result['Standorttyp']];
$posts_gf = new WP_Query(array(
'post_type' => 'tarife',
'posts_per_page' => 6,
'post_status' => 'publish',
'post__in' => $products,
'orderby' => 'title',
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'tarif_kategorie',
'field' => 'slug',
'terms' => 'glasfaser',
),
),
));
$street = utf8_encode($result['Strasse']);
$houseNo = $result['Hausnummer'];
$postCode = $result['Plz'];
$city = $result['Ort'];
$response = '
<h3>inside return</h3>
<section class="regular slider">';
// Zeige die Glasfaser-Tarife
if ( $posts_gf->have_posts() ) :
while ( $posts_gf->have_posts() ) : $posts_gf->the_post();
$response .= '
<div class="item col-md-4">
Produkt
</div>
';
endwhile;
wp_reset_postdata();
else:
$response .= '';
endif;
return array('html' => $response);
}
}
编辑: 对于轮播,我在我的functions.php(wordpress)中插入了3个文件
wp_enqueue_style( 'xxx-slider', get_stylesheet_directory_uri() . '/css/slick.css', array(), '20170925' );
wp_enqueue_style( 'xxx-slidertheme', get_stylesheet_directory_uri() . '/css/slick-theme.css', array(), '20170925' );
...
wp_enqueue_script( 'xxx-sliderjs', get_template_directory_uri() . '/js/slick.min.js', array(), '20190218', true );
- 所有这些文件都加载到页眉/页脚中。
- 轮播应该在已经加载的 php 中运行。
- 脚本来自http://kenwheeler.github.io/slick/,它在“已加载”文件中运行。但不在 ajax(?) 内部。
【问题讨论】:
-
你在浏览器中查看源代码了吗? JS部分是否出现在那里?但是,你到底想输出什么样的 JS?因为在这种情况下,也许另一种方法会更好。
-
@ChrisG 是的。出现 JS 代码(例如警报),并且在页脚和页眉中包含所有文件。
-
@ChrisG 在第一步中,发出警报时对我来说就足够了。那么这可能是无法识别“外部”js文件中的代码的解决方案。
-
轮播代码是如何插入到主文档中的?你是通过 AJAX 加载它吗?因为在这种情况下,JS 代码不会自行运行。
In the first step, it would be enough for me when the alert is issued.我明白这是你的方法,但我仍然认为另一种方法更适合这里。如:轮播代码不是 AJAX HTML 的一部分,但已经加载到<script>中,插入轮播后,会调用 init 代码。 -
@ChrisG 我已经编辑了我的问题。评论太混乱了:-D
标签: javascript php wordpress return response