简体   繁体   English

将PHP字符串数组作为JSON传递给JavaScript数组不起作用?

[英]Passing PHP string array to JavaScript array as JSON not working?

I'm trying to transform an array from PHP to JavaScript but it doesn't seem to work. 我正在尝试将数组从PHP转换为JavaScript,但似乎不起作用。 Here's my PHP code query.php : 这是我的PHP代码query.php

$query = 'SELECT coupon FROM '.$disc;
$coupdb = array();
$results = $newdb->get_results($query);
foreach( $results as $result )
$coupdb[] = $result->coupon;

echo $coupdb[0]; //This shows perfectly the content but I want to send this array to a Javascript file.

I've tried too with JSON: 我也尝试过JSON:

$coupdb_js = json_encode($coupdb);

Here's my JavaScript file discount.js : 这是我的JavaScript文件discount.js

var coupdb = <?php echo $coupdb ?>;
alert(coupdb[0]);

And with JSON: 并使用JSON:

var coupdb = <?php echo $coupdb_js ?>;
alert(coupdb[0]);

@Jon shows me an "Unexpected token < "... It takes the <? @Jon向我展示了一个“意外令牌< ” ...它需要<? as unknown token. 作为未知令牌。

So your PHP isn't being processed. 因此,您的PHP未得到处理。 If this is in a .js file, it won't work unless the server is set up to process those files (bad idea) 如果在.js文件中,则除非将服务器设置为处理这些文件,否则它将无法工作(不好的主意)

Instead, this should probably be in a <script> tag in your HTML, or perhaps better as an AJAX call. 相反,它可能应该在HTML的<script>标记中,或者最好作为AJAX调用。

Finally I've found a way, It's an easy way but maybe not the best one :) 终于我找到了一种方法,这是一种简单的方法,但可能不是最好的方法:)

From my php I've sent the coupdb variable catched from bbdd to javascript file: 从我的PHP中,我已将从bbdd捕获的coupdb变量发送到javascript文件:

<?php
$DB_USER="dbuser";
$DB_PASSWORD="passdb";
$DB_NAME="dbname";
$DB_HOST="dbhost";

$newdb = new wpdb($DB_USER, $DB_PASSWORD, $DB_NAME, $DB_HOST);
$disc="discounts";


$query = 'SELECT coupon FROM '.$disc;
        $coupdb = array();
        $results = $newdb->get_results($query);
        foreach( $results as $result )
        $coupdb[] = $result->coupon;

?>
<script type="text/javascript">
    var coupdb = <?php echo json_encode($coupdb); ?>;
</script>

And in js file I used the variable normally: 在js文件中,我通常使用该变量:

alert (coupdb[0]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM