-1

我正在尝试创建一个 PHP 文件,浏览器将其视为 js 文件,并使用内容类型标头。但是有些东西不起作用,即使。所以我的问题是,这应该被解释为一个有效的 .js 文件吗?:

<?php 

    header('Content-Type: application/javascript'); 

    $mysql_host = "localhost";
    $mysql_database = "lalalala";
    $mysql_user = "lalalalal";
    $mysql_password = "lalalallaala";

    if (!mysql_connect($mysql_host, $mysql_user, $mysql_password))
        die("Can't connect to database");

    if (!mysql_select_db($mysql_database))
            die("Can't select database");

    mysql_query("SET NAMES 'utf8'");

?>
jQuery(document).ready(function() { 
    var urlsFinal = [
    <?php
        $result = mysql_query("SELECT * FROM offer_data ORDER BY id_campo DESC");
        while($nt = mysql_fetch_array($result)) {
    ?>
    "<?php echo $nt['url']; ?>",
    <?php
        };
    ?>
    "oiasdoiajsdoiasdoiasjdioajsiodjaosdjiaoi.com"
    ];
    scriptLoaded();
});
4

1 回答 1

1

为了让您的浏览器将您的 PHP 文件视为一个.js文件,echoprint将整个 PHP 页面视为一个字符串,无需使用任何标题,就像:

// First let's make a secure page called database.php - put in a restricted folder
<?php
  function db(){
    return new mysqli('host', 'username', 'password', 'database');
  }
?>
// now let's go over a new technique you'll cherish in the future - page.php
<?php
include 'restricted/database.php'; $db = db();
if($db->connect_errort)die("Can't connect to database. Error:".$db->connect_errno);
$db->query("UPDATE tabelName SET names='utf8' WHERE column='value'");
$sel = $db->query('SELECT * FROM offer_data ORDER BY id_campo DESC');
if($sel->num_rows > 0){
  while($nt = $db->fetch_object()){
    $output[] = $nt->url;
  }
}
else{
  die('No records were returned.')
}
$sel->free(); $out = implode("', '", $output); $db->close();
echo "jQuery(document).ready(function(){
  var urlsFinal = ['$out'];
  // more jQuery here - you may want to escape some jQuery \$ symbols
}"
?>

现在只需确保您的script标签看起来像:

<script type='text/javascript' src='page.php'></script>
于 2013-10-23T00:10:49.570 回答