使用jquery在div中显示php脚本结果

时间:2017-09-30 09:47:39

标签: javascript php jquery wordpress

我是编码的初学者。我正在使用海狸生成器主题在WordPress网站上工作。我的挑战是显示登录表单(当用户未登录时)和登录时的用户名,以及具有类"标题文本"的标题的特定区域。 这是我的PHP代码,位于名为" file.php"

的文件中



<?php
if(is_user_logged_in()) {
	$user = wp_get_current_user();
	$var1 = "<p>Welcome <?php echo $user->display_name; ?></p>
			<p><a href='/login/login.php?logout=true'>Click here to log out</a></p>";
	$var2 = "<form action='login.php' method='post'>
			   <input type='text" autocomplete='off' placeholder='Username' name='username'/>
			   <input type='text' autocomplete='off' placeholder='Password' name='password'/>
			   <button type='submit' value='Submit'>Submit</button>
			</form>";
	echo echo json_encode($var1);
} else {
	echo echo json_encode($var2);
}
?>
&#13;
&#13;
&#13;

这是javascript

&#13;
&#13;
<script type="text/javascript">
jQuery(document).ready(function($){

	function displayAccess() {
    $.get("login/file.php");
    return false;
}

	if(<?php echo json_encode($var1); ?>) {
		var variable1 = <?php echo json_encode($var1); ?>;
		document.getElementByClassName("header-text").innerHTML = variable1; 
	}
	if(<?php echo json_encode($var2); ?>){
	    var variable2 =  <?php echo json_encode($var2); ?>;
	    document.getElementByClassName("header-text").innerHTML = variable2;
	}
});

</script>
&#13;
&#13;
&#13; 我需要帮助来纠正我的脚本。谢谢!

1 个答案:

答案 0 :(得分:0)

在这种情况下,javascript不需要jquery,因为无论如何登录状态会在重新加载时发生变化。

您需要的只是改变您的PHP代码:

<?php
/* put this to your template file (e.g. header.php) */

if(is_user_logged_in()) {
    $user = wp_get_current_user();
    /* change $var1 to echo it via html block inside php */
    ?>
    <p>Welcome <?php $user->display_name; ?></p>
    <p><a href="/login/login.php?logout=true">Click here to log out</a></p>
    <?php
    /* cut $var2 because it is not accessible in the else clause */
} else {
    /* 

    paste $var2 here and echo it

    btw: 
    * For tags that are self-closing, the forward slash should have exactly one space preceding it (https://make.wordpress.org/core/handbook/best-practices/coding-standards/html/#self-closing-elements)
    * use single or double quotes – make a decision!

    */
    ?>
    <form action="login.php" method="post">
        <input type="text" autocomplete="off" placeholder="Username" name="username" />
        <input type="text" autocomplete="off" placeholder="Password" name="password" />
        <button type="submit" value="Submit">Submit</button>
    </form>
    <?php
}
?>