2017-11-11 18 views
-1

我想在JavaScript中添加一些PHP,但是,我目前使用的那個不起作用,並且想知道您是否可以提供幫助。將PHP加入JavaScript

這是我到目前爲止有:

$(document).ready(function() { 
setTimeout(function() { 
    $("body").addClass("ready"); 
}, 1700); 
setTimeout(function() { 
    $(".splash h1").html("Hi <?php echo '$first_name'?>"); 
    setTimeout(function() { 
    $(".splash h1").html("Welcome to your Profile"); 
    }, 1500); 
}, 900); 
}); 

變量first_name已定義和PHP頁面會顯示上完全正常。

這裏是PHP代碼

<?php 
/* Displays user information and some useful messages */ 
session_start(); 

// Check if user is logged in using the session variable 
if ($_SESSION['logged_in'] != 1) { 
    $_SESSION['message'] ='<br>You must be logged in before accessing that page!'; 
    header("location: login.php"); 
} 
else { 
    $title = $_SESSION['title']; 
    $first_name = $_SESSION['first_name']; 
    $last_name = $_SESSION['last_name']; 
    $email = $_SESSION['email']; 
    $school_name = $_SESSION['school_name']; 
    $class = $_SESSION['class']; 
    $school_admin = $_SESSION['school_admin']; 
    $position = $_SESSION['position']; 
    $active = $_SESSION['active']; 
    $staff = $_SESSION['staff']; 
    $grav_hash = md5("$email"); 
} 
?> 
+1

''$ first_name''刪除引號 –

+0

完成 - 仍然沒有工作,只能用彈出‘嗨’。 – Tom

+1

你沒有在末尾添加';'bud – Samuel

回答

-1
$(document).ready(function() { 
    setTimeout(function() { 
    $("body").addClass("ready"); 
    }, 1700); 
    setTimeout(function() { 
    $(".splash h1").html("Hi <?php echo '{$first_name}'; ?>"); 
    setTimeout(function() { 
    $(".splash h1").html("Welcome to your Profile"); 
    }, 1500); 
}, 900); 
}); 

您還沒有結束與分號回聲。這是錯誤。

+0

添加了分號,但不工作仍然只顯示「嗨」,然後移動到「歡迎使用您的配置文件」。 – Tom

+0

你能否顯示你的php代碼? –

+0

您的語法錯了@mayankjain –

0

刪除變量周圍的分號,並確保它已被定義。

<?php 

$first_name = "Tom"; 

?> 

$(document).ready(function() { 
    setTimeout(function() { 
     $("body").addClass("ready"); 
    }, 1700); 
    setTimeout(function() { 
     $(".splash h1").html("Hi <?php echo $first_name; ?>"); 
     setTimeout(function() { 
     $(".splash h1").html("Welcome to your Profile"); 
     }, 1500); 
    }, 900); 
    }); 
+0

變量是在php文件中使用的,我必須在這個js文件中定義它嗎? – Tom

+0

如果它是一個單獨的JS文件,您必須在JS文件上定義它。 –

+0

它適合你嗎? –

0

如果您使用的是外部.js文件,除非您在.htacess文件中更改某些內容,否則這是不可能的。還有另一種更簡單的方法。 使用.php文件並在開始處添加header("Content-type: text/javascript");並使用簡單的echo'your js code';編寫腳本,您可以在單個文件中混合使用php和javascript。

如果您使用.php文件並使用<script></script>只需使用<?php $yourphpcode; ?>並添加您的代碼。

我希望我已經幫你這個:-)