欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php文件与HTML页面的数据交互

程序员文章站 2022-12-22 21:31:00
php获取HTML页面返回的数组并写入文档以及HTML页面通过json获取php的变量。 ......

注意:首先需要保证本地配置了php开发环境,如wamp开发环境

wamp配置:

 

php获取html页面返回的数组并写入文档

 

html发送使用post发送)

 

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>

<body>
    <div class='search-choose' id='search_choose'>
        <ul> 
            <li id='search_1' class='search-selected'><a href='#'>dog</a></li>
            <li id='search_2'><a href='#'>cat</a></li>
        </ul>
    </div>
    
    <script type='text/javascript'>
      searcharray = document.getelementsbytagname('li');//获取名字为’li’的所有标签项并存入数组
      var writearray = [];
      for(var i = 0;i<searcharray.length;i++){
          writearray[i] = searcharray[i].innertext;//获取标签内容writearray = ['dog','cat'];
      }
    
      //使用post将数组writearray发送到php文件servertest.php
      var request = new xmlhttprequest();
      request.open("post", "servertest.php");
      var q = "data=" + writearray;//  q="name"+ value;
      //发送内容体由name+value组成,此处name为data,value为writearray
      request.setrequestheader("content-type","application/x-www-form-urlencoded");
      request.send(q);
      request.onreadystatechange = function() {
          if (request.readystate===4) {
          if (request.status===200) { 
          } else {
                  alert("发生错误:" + request.status);
              }
          } 
      }
    </script>
</body>
</html>

 

:关键操作

var request = new xmlhttprequest();

request.open("post", "servertest.php");

var q = "data=" + writearray;// 生成信息体q = “name “+ value

request.setrequestheader("content-type","application/x-www-form-urlencoded");

request.send(q);

//html页面post发送内容后,php通过超全局变量 $_get $_post收集

 

php接收(使用超全局变量$_get $_post收集

<?php
//设置页面内容是html编码格式是utf-8
header("content-type: text/plain;charset=utf-8"); 
//判断如果是get请求,则执行getmethod();;如果是post请求,则执行postmethod()。
//$_server是一个超全局变量,在一个脚本的全部作用域中都可用,不用使用global关键字
if ($_server["request_method"] == "get") {
    getmethod();
} elseif ($_server["request_method"] == "post"){
    postmethod();
}
function searchshow(){    
}
function postmethod(){
    $filename = 'save.txt';
//使用超全局变量 $_get 和 $_post收集name对应的value,如下
    $searchwrite = $_post["data"];
//将获取的html返回内容$searchwrite写入文档save.txt
    file_put_contents($filename, $searchwrite);
    $content = file_get_contents($filename);
    echo $content;
}

:关键操作

$searchwrite = $_post["data"]

使用超全局变量 $_post收集name对应的value放入$searchwrite,于是得到了html页面发送的数据,可以用了

 

html页面通过json获取php的变量

 

php发送(通过echo返回json格式的数据对)

<?php
header('access-control-allow-origin:*');
header('access-control-allow-methods:post,get');
header('access-control-allow-credentials:true'); 
header("content-type: application/json;charset=utf-8"); 
if ($_server["request_method"] == "get") {
    getmethod();
} elseif ($_server["request_method"] == "post"){
    postmethod();
}
function getmethod(){    
    $filename = 'search_save.txt';//假设文件内容为dog,cat,pig,人
    if (file_exists($filename)) {
        $content = file_get_contents($filename);
        $pattern = '/[\x{4e00}-\x{9fa5}_a-za-z0-9]+/u';
        //[\x{4e00}-\x{9fa5}_a-za-z0-9]匹配中文、下划线、字母、数字
        preg_match_all($pattern, $content, $matches);
        $searchread = $matches[0];//通过正则表达式提取存储列表到$searchread数组['dog','cat','pig','人']
        $defaultsearch = $searchread[0];
        $result = '{"success":false,"defaultsearch":""}';
        if($_get["data"]){
            $result = '{"success":true,"defaultsearch":"'.$defaultsearch.'"}';
        }
    }
    echo $result;//echo返回json格式化数据对{"success":true,"defaultsearch":"'.$defaultsearch.'"}
 } 
functionpostmethod(){
}

:关键操作

$result = '{"success":true,"defaultsearch":"'.$defaultsearch.'"}';//将待返回内容改为json格式

   echo $result;//html页面的json部分将从echo的输出获取json格式化数据对,因此echo输出内容需要为json格式

html接收通过get接收php echo返回的json格式的数据对)

 

 <script type='text/javascript'>
        $(document).ready(function(){ 
            $.ajax({ 
                type: "get",     
                url: "default_search.php?data=" + value,//value为html向url发送的内容体,在php中可以通过超全局变量收集
                datatype: "json",
               //data为php使用echo返回的json格式的数据对,通过data.name的形式即可以使用name对应的value
           success: function(data) {
            if (data.success) {
              alert(data.defaultsearch);            
            }
          },
                error: function(jqxhr){     
                   alert("发生错误:" + jqxhr.status);  
                },     
            });
        });
</script>

 

:关键操作

$.ajax({

   type: "get",

        url: "default_search.php?data=" + "searcharray",

        datatype: "json",

        success: function(data) {

       if(data.success){alert(data.defaultsearch);}

//dataphp使用echo输出的json格式的数据对,通过data.name的形式即可以使用name对应的value

         },

         error: function(jqxhr){     

           alert("发生错误:" + jqxhr.status);  

         },     

    });

});