网页APP与后端JSON通讯方案

后端api.php,用于对客户端请求进行处理

<?php
  include_once( 'api.function.php' );
  header("Content-type:application/json");
  header("Access-Control-Allow-Origin: *");
  $action = $_GET['action'];
  if($action == "" || $action == NULL)
  {
    SendReply(ERR_GENERAL,"");
  }
  else if(!function_exists($action))
  {
    SendReply(ERR_GENERAL,"");
  }
  call_user_func($action);

  function hello_world()
  {
    $data = "HELLO WORLD!";
    SendReply(ERR_NOERROR,$data);
  }
  function hello()
  {
    if(!v( 'msg' )) SendReply(ERR_GENERAL,"");
    $msg = v( 'msg' );
    $data = $msg;
    SendReply(ERR_NOERROR,$data);
  }
?>

后端api.function.php,用于定义常规函数

<?php
  define("ERR_NOERROR",0);
  define("ERR_GENERAL",1);
  function SendReply($err_code = 0, $content = "")
  {
    $reply = array(
      "ERROR" => $err_code,
      "CONTENT" => $content
    );
    echo json_encode($reply);
    exit();
  }
  function v( $str )
  {
    return isset( $_REQUEST[$str] ) ? $_REQUEST[$str] : false;
  }
?>

前端javascript,需要jQuery

function hello_world()
{
  $.post( 'api.php?action=hello_world' , {} , function( data )
  {
    console.log(data);
  });
}

function hello(string)
{
  $.post( 'api.php?action=hello' , {'msg':"say sth"} , function( data )
  {
    console.log(data);
  });
}

用itchat做一个简单的关键词回复微信机器人

itchat组件:https://github.com/littlecodersh/ItChat
下载后根据安装教程

pip install itchat

安装itchat
新建wxbot.py

#coding=utf8
import itchat
import time
@itchat.msg_register('Text')
def text_reply(msg):
  f = open("words.txt")  
  for line in f:
    splited = line.split(',')
    if splited[0] in msg['Text']:
      return splited[1].replace("\n", "")
  f.close()
itchat.auto_login(True, enableCmdQR=True)
itchat.run()

新建words.txt(注意文件编码,否则会导致乱码)
用以下格式编辑关键词回复

关键词1,回复1
关键词2,回复2
关键词3,回复3

运行

python wxbot.py

登录后即可。

jQuery实现垂直居中+iframe高度自适应

jQuery垂直居中

if ($(".ClassName").height() = $(window).height()) $(".ClassName").css("marginTop",$(window).height()/2 - $(".ClassName").height()/2);

jQuery iframe高度自适应

$(document).ready(
  function()
  {
    $(window).resize(function(){$(".iframeName").height($(window).height());});
    $(".iframeName").load(function(){$(this).height($(window).height());});
  }
);