

ajax使用说明及注意事项
注:调试ajax代码时要注意清空浏览器缓存,由于浏览器会缓存js文件,不清空缓存,当你改了js后,浏览器调用的还是上次的js文件,会出现莫名故障
注2:如何没有保存为单独的js文件不用清缓存,但要刷新页面
主要优点:是可以异步与服务器交换数据,而不用刷新页面。
ajax代码的调试
1)打开chrome的开发者工具的控制台可调试ajax代码,但要加入下面xhr.onreadystatechange开始到下面14行的代码以便在控制台显示故障
2)ajax动态输出的内容右击网页--显示源码是看不到的,可以在开发者工具的元素下面找到输出的div查看,也可以右击复制出来
f12常见错误:
Uncaught ReferenceError: upuserval is not defined //说是函数upuserval函数没有定义即没找到函数,可明明有
function upuserval(userid,classid)
{
var class = document.getElementById(classid).value; //class是关键字,不能使用,可把class改成classval
alert(class);
}
ajax提交到PHP页面的值与PHP页面获取到的值不一样,
不管ajax提交的值为多少,PHP页面得到的参数值始终为1 ,
原因:$val1 = isset($_GET['val1']);,改为:$val1 = isset($_GET['val1']) ? $_GET['val1'] : 'aa'; //前面只判断是否有值但没有赋值
1. 使用GET方式提交参数linkid到record_click.php页面的代码:
function recordClick(linkid) {
// 发送 AJAX 请求到服务器端
const xhr = new XMLHttpRequest();
//显示调试信息到控制台及请求页面返回值到id名为myDiv的div中
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
const myDiv = document.getElementById("myDiv");
if (xhr.status === 200) {
if (myDiv) {
myDiv.innerHTML = xhr.responseText; //这里是将record_click.php页面返回的内容显示到id为myDiv的div中,list.php中要有这个id的div才能显示
} else {
console.error("Element with id 'myDiv' not found.");
}
} else {
console.error("Error: " + xhr.status + " - " + xhr.statusText);
}
}
}
xhr.open("GET", `record_click.php?linkid=${encodeURIComponent(linkid)}`, true);
xhr.send();
}
可将上面代码保存为单独的文件script.js放在public目录下,路径public/script.js, 在list.php页面使用如下代码引用,也可直接放到<script></script>中
<script src="public/script.js" defer></script> //在title行下加入这行引用,放单独js文件中是不需加<script></script>
注:****上面第5行这里xhr.open中打开的文件record_click.php可用相对路径,这里的相对是指相对于调用文件list.php的位置,而不是相对于script.js的位置
精简上面的GET方式代码不输出调试信息到控制台,不面输出record_click.php的返回值到id名为myDiv的div中
function recordClick(linkid) {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {}
}
xhr.open("GET", `record_click.php?linkid=${encodeURIComponent(linkid)}`, true);
xhr.send();
}
2. 使用POST方式提交参数linkid到record_click.php页面的代码:
<script> //直接在title标签下加入这段
function recordClick(linkid) {
// 发送 AJAX 请求到服务器端
const xhr = new XMLHttpRequest();
//显示调试信息到控制台及请求页面返回值到id名为myDiv的div中
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
const myDiv = document.getElementById("myDiv");
if (xhr.status === 200) {
if (myDiv) {
myDiv.innerHTML = xhr.responseText;
} else {
console.error("Element with id 'myDiv' not found.");
}
} else {
console.error("Error: " + xhr.status + " - " + xhr.statusText);
}
}
}
xhr.open("POST", `record_click.php`, true); //post方式不能把参数加到请求文件后面要放在send中
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //Post方式需要设置请求头,否则PHP页无法获取参数
//进行URL编码
const params = `linkid=${encodeURIComponent(linkid)}`; //encodeURIComponent用来对参数中特殊字符进行编码
xhr.send(params); //send()方法用于发送请求
}
</script>
精简上面的代码,不再调试信息及请求页面返回值到id名为myDiv的div中
function recordClick(linkid) {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {}
}
xhr.open("POST", `record_click.php`, true); //post方式不能把参数加到请求文件后面要放在send中
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //Post方式需要设置请求头,否则PHP页无法获取参数
xhr.send(`linkid=${encodeURIComponent(linkid)}`); //send()方法用于发送请求
}
3. 上面GET与POST请示页面record_click.php代码
<?php
require_once "admin/connMydata.php";
if (isset($_POST['linkid'])) {
$linkid = $_POST['linkid'];
// if (isset($_GET['linkid'])) { //注:这里的$_GET不能写成$GET,写错不提示错误,但获取不到数据,不易排查
// $linkid = $_GET['linkid'];
$sql = "UPDATE ct_txthtml SET click_count = click_count + 1 WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $linkid);
$stmt->execute();
$stmt->close();
}
?>
多参数下的GET与POST上传,示例见:site\w80\a\ajax\
POST方式:
function test(id,id2
const params = `id=${encodeURIComponent(id)}&id2=${encodeURIComponent(id2)}`; //encodeURIComponent用来对参数中特殊字符进行编码
xmlhttp.send(params); //send()方法用于发送请求
GET方式:
function test(id,bb)
xmlhttp.open("GET",`try/getReceive.php?id=${encodeURIComponent(id)}&bb=${encodeURIComponent(bb)}`,true); //encodeURIComponent用来对参数中特殊字符进行编码
===============================================================================================================
3. 通过ajax修改某记录的多个字段的值,详见:E:\FTP\site\w80\aa\cjzs\cjzsShowdata.php
function upuserval(lid,userid,classid)
{
var user = document.getElementById(userid).value; //获取变量id指向的输出框的值传给变量user
var classval = document.getElementById(classid).value; //注:不能使用关键定class为变量名,所在这里class字段改为classval
const xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);//将config/upuserval.php页面的返回以弹框的形式显示出来
//document.getElementById("myDiv").innerHTML=xmlhttp.responseText; 将返回的数据写入某个div
}
}
xmlhttp.open("GET",`config/upuserval.php?user=${encodeURIComponent(user)}&lid=${encodeURIComponent(lid)}&&classval=${encodeURIComponent(classval)}`,true);
xmlhttp.send(); //将参加通过GET方式传给upuserval.php页面,详见E:\FTP\site\w80\aa\cjzs\config\upuserval.php
}
//通过点击button,调用上面的函数获取下面input框中的值通过GET方式传给upuserval.php页面
注:当有多个input框的值要传输时,每个input框的id值不能相同,可以用字段名+记录id作为input框的id
<td><input type='text' id='class" . $row["lid"] . "' value='" . $row["class"] . "' maxlength='50' size='10' title='" . $row["class"] . "' /></td>
<td><input type='text' id='user" . $row["lid"] . "' value='" . $row["user"] . "' maxlength='50' size='10' title='" . $row["user"] . "' /></td>
<button type='button' onclick='upuserval(\"" . $row["lid"] . "\",\"user" . $row["lid"] . "\",\"class" . $row["lid"] . "\")'>修改</button>