在html网页上从javascript编辑和显示php文件中的变量


Edit and display variable in php file from javascript on html web page

我想要的是在服务器上的php文件中创建一个名为"likes"的变量

然后,在我的html网页上,我想有一个赞按钮,当点击时,它使用javascript编辑php文件中的变量"赞",并添加1。页面上的点赞按钮上方会有一个小地方,显示点赞总数。

我有什么:

PHP文件:"index.PHP"

<?php
$likes=0;
/** Load likes page START */
require( dirname( __FILE__ ) . '/likespagestart.html' );
echo $likes;
/** Load likes page END */
require( dirname( __FILE__ ) . '/likespageend.html' );
?>

HTML文件:"likepagestart.HTML"

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Likes Page</title>
<script type="text/javascript">
var count = 0;
function countClicks() {
 count = count + 1;
    document.getElementById("p2").innerHTML = count;
}
</script>
</head>
<body>
This is the likes page!
<br/>
Number of likes: <p id="p2">0</p>

HTML文件:"likepageend.HTML"

<br/>
<a href="javascript:countClicks();">Like</a>
</body>
</html>

在我的网站上查看:www.stevenhower.com/phpinclude/likes(第一个0只是javascript,第二个0是php变量。

所以现在,我只有一个愚蠢的javascript函数,实际上无法编辑php文件中的变量。。。

创建一个url,该url将处理所有后端逻辑以更新您的"点赞",然后创建一个带有post方法的ajax调用来访问该url。我建议将jQuery javascript框架与此方法一起使用:http://api.jquery.com/jquery.post/

$.ajax({
  type: "POST",
  url:'/update_likes.php',
  data: {
   'likes': updated_counter
  },
  success: function(){
   // Update view logic
  },
  dataType: 'json'
});

类似的东西