Heim  >  Artikel  >  php教程  >  php+ajax实现微信上墙

php+ajax实现微信上墙

WBOY
WBOYOriginal
2016-06-21 08:48:321023Durchsuche

好久就想实现这个功能了,可是一直没心情,好在收到网易实习的offer,于是心情大好,实现了这个功能来和大家共享。大家可以先看效果吧:只要关注微信公众帐号say_magic,


然后打开网址http://www.saymagic.cn/weixin/wall.php,在公众号里回复:上墙+您要说的话,您就会发现您说的话会同步到上面的网址上。


整个流程大概是这样:

公众号的后台接收到消息并将消息存入数据库,而前台呢,则使用js的setTimeout函数进行循环的使用ajax向后台get数据来获取数据库的最新数据,当明白整个原理后,就显得很简单,接下来看一下主要的代码:

wall.php(微信墙页面 )

<?php
     include_once("sql.php");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>微信墙</title>
<style>
    
#msgBox div {
	padding: 19px;
	margin-bottom: 20px;
	background: #aaaaaa;
	border: 2px solid #e3e3e3;
	-webkit-border-radius: 4px;
	-moz-border-radius: 4px;
	border-radius: 4px;
	-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.05);
	-moz-box-shadow: inset 0 1px 1px rgba(0,0,0,0.05);
	box-shadow: inset 0 1px 1px rgba(0,0,0,0.05);
    filter:alpha(opacity=60);
     /* CSS3 standard */
     opacity:0.4;
     font-style:italic;
     font-size:15px;
     width:50%;
}
    
body{
	background: url(bg_main.jpg);
}
</style>
</head>
<body>
    <center>
<p id="msgBox">
<?php
$wxQuery = "SELECT * FROM wx_note ORDER BY id DESC LIMIT 25";//把wx_msg更改掉
$wxResult =$mysql->query($wxQuery);
while ($wxRow=mysql_fetch_row($wxResult)) {
    $lastID or $lastID = $wxRow[0];//0代表数据库中的id,这个要和你自己数据库相对应
    $content = $wxRow[4];//4也是一样的
	echo "<p>",$content,"</p>\n";
}
$lastID = (int)$lastID;
?>
</p>
 
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
<script>
var lastID = <?php echo $lastID; ?>;
function getMessages() {
       $.ajax({
           url: "message.php?lastID=" + lastID + "&v=" + (new Date()/1),
        dataType: "json",
        error: function(){  
            alert("Error loading JSON document");  
        },  
        success: function(data){//如果调用php成功            
				$.each(data,function(i,n){
                        message = "<p>" + n + "</p>";
                        $(message).prependTo("#msgBox").hide().slideDown("slow");
                       	lastID = i;
				});


        }
    });	
	window.setTimeout(getMessages, 5000);
}
getMessages();
</script>
 </center>
</body>
</html>

mysql操作文件sql.php:
<?php
$hostname = "***********";
$dbuser = "***********";
$dbpass = "***************";
$dbname = "************"; 
$mysql = new mysql( $hostname,$dbuser,$dbpass,$dbname,"","");

class mysql {
    private $db_host; //数据库主机
    private $db_user; //数据库用户名
    private $db_pwd; //数据库用户名密码
    private $db_database; //数据库名
    private $conn; //数据库连接标识;
    private $result; //执行query命令的结果资源标识
    private $sql; //sql执行语句
    private $row; //返回的条目数
    private $coding; //数据库编码,GBK,UTF8,gb2312
    private $bulletin = true; //是否开启错误记录
    private $show_error = false; //测试阶段,显示所有错误,具有安全隐患,默认关闭
    private $is_error = false; //发现错误是否立即终止,默认true,建议不启用,因为当有问题时用户什么也看不到是很苦恼的
  
    /*构造函数*/
    public function __construct($db_host, $db_user, $db_pwd, $db_database, $conn, $coding) {
        $this->db_host = $db_host;
        $this->db_user = $db_user;
        $this->db_pwd = $db_pwd;
        $this->db_database = $db_database;
        $this->conn = $conn;
        $this->coding = $coding;
        $this->connect();
    }
  
    /*数据库连接*/
    public function connect() {
        if ($this->conn == "pconn") {
            //永久链接
            $this->conn = mysql_pconnect($this->db_host, $this->db_user, $this->db_pwd);
        } else {
            //即使链接
            $this->conn = mysql_connect($this->db_host, $this->db_user, $this->db_pwd);
        }
  
        if (!mysql_select_db($this->db_database, $this->conn)) {
            if ($this->show_error) {
                $this->show_error("数据库不可用:", $this->db_database);
            }
        }
        //mysql_query("SET NAMES $this->coding");
    }
  
    /*数据库执行语句,可执行查询添加修改删除等任何sql语句*/
    public function query($sql) {
        if ($sql == "") {
            $this->show_error("SQL语句错误:", "SQL查询语句为空");
        }
        $this->sql = $sql;
        $result = mysql_query($this->sql, $this->conn);


        if (!$result) {


            //调试中使用,sql语句出错时会自动打印出来
            if ($this->show_error) {
                $this->show_error("错误SQL语句:", $this->sql);
            }
        } else {
             $this->result = $result;
        }
        return $this->result;
    }
  
}
?>


不断从数据库获取最新数据的文件message.php.


<?php
 header("Content-Type:text/html; charset=UTF-8");//utf-8,使中文不会变成乱码
/**************************************************************
 *
 *	使用特定function对数组中所有元素做处理
 *	@param	string	&$array		要处理的字符串
 *	@param	string	$function	要执行的函数
 *	@return boolean	$apply_to_keys_also		是否也应用到key上
 *	@access public
 *
 *************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
    static $recursive_counter = 0;
    if (++$recursive_counter > 1000) {
        die("possible deep recursion attack");
    }
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            arrayRecursive($array[$key], $function, $apply_to_keys_also);
        } else {
            $array[$key] = $function($value);
        }
 
        if ($apply_to_keys_also && is_string($key)) {
            $new_key = $function($key);
            if ($new_key != $key) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
    }
    $recursive_counter--;
}


function JSON($array) {
	arrayRecursive($array, "urlencode", true);
	$json = json_encode($array);
	return urldecode($json);
}


$lastID = (int) $_GET["lastID"];
include_once("sql.php");
$backValue=array();


$wxQuery = "SELECT * FROM wx_note WHERE id > ".$lastID." ORDER BY id LIMIT  3";
$wxResult = $mysql->query($wxQuery);
while ($wxRow=mysql_fetch_row($wxResult)) {
	$recordID = $wxRow[0];
	$content = $wxRow[4];
    //$xml=$content;
    $backValue[$recordID ] = $content;


}


echo JSON($backValue);


?>



最后,如果需要的话,还有背景图片:/program/UploadPic/2014-3/2014317135337634.jpg.


当然,这里说的只是后端的部分,在处理微信消息上,你还需要把收到的消息存入数据库,这应该没什么难度,就不放代码了。这里一定要记得和刚才操作的方法中的数据格式相对应,这是最容易出错的了。好的,如果有什么疑问的话,欢迎留言。


转载请注明:我的原博客链接http://blog.saymagic.cn/blog.php?id=58




Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:phpexcel图形图表(一)入门Nächster Artikel:PHP基础之Autoload