AJAX和PHP传输数据

html 文件代码:
$.get(‘http://127.0.0.1/NanHaiFishStatistics/php/first.php‘, { “name”: “John”, “time”: “2pm” });
第一个参数是php文件的地址,第二个参数是被传输的数据
php 文件代码:
<?php
$username=$_GET[“name”]; //获取name对应的值
$usertime=$_GET[“time”]; //获取time对应的值
$myarr =array( //存储到数组中
“myname” => $username,
“mytime” => $usertime
);
$text =var_export($myarr,true); //将数组直接保存为数组形式存储到文本文件中
echo file_put_contents(“test.txt”,$text); //第一个参数是文件名,第二个参数是数据

将数组存储为json文件:
$baseJson = json_encode($baseArr);
file_put_contents(“$fileName.json”,$baseJson);
将json转化为数组:
$baseJson = file_get_contents(“$fileName.json”);
$data = json_decode($baseJson, true);
注意事项:
1.为了检验数据是否正常传输,新手往往会在php文件中将接收到的数据打印出来,
比如: printf($_GET[“name”]);
这个时候,在浏览器打开php文件,网页显示未定义变量name;这是因为HTTP是短连接,当直接访问php的时候,该变量已失效。所以,为了检验代码的正确性,最好直接将代码写入文件中。
2.写入文件的时候,只保存了键值对中的值。
file_put_contents(“test.txt”,$myarr); //将未处理过的数组直接写入文件
只保存了键的值,键名没有进行存储。
3.用变量来作为文件名
$fileName =$_GET[“formNum”];
file_put_contents(“$fileName.txt”,$baseText);

您的支持将鼓励我继续创作!