记录一下Javascript原生post请求写法
Javascript
let xhr = new XMLHttpRequest(); // 创建XHR对象 xhr.onreadystatechange = function () { if (xhr.readyState == 4) { // 4表示此次请求结束 console.log("后端返回的结果:"+this.responseText); /** 你的逻辑代码 **/ let result = JSON.parse(this.responseText);// 后端返回的结果为字符串,这里将结果转换为json if(result.code == 1){ // 这里我通过code来标识结果 // 输出后端返回的用户名 console.log("用户名:"+result.data["username"]); // 输出后端返回的密码 console.log("用户名:"+result.data["password"]); } /** 你的逻辑代码End **/ } }; xhr.open( // 打开链接 "post", "server.php", // 后端地址 true ); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置请求头 xhr.send( // 设置需要携带到后端的字段,字符串形式 "username="+ "火柴炮炸牛屎" + "&password="+ "123456" // 注意:字段之间需要加上 “ & ” 字符 );
后端 PHP 接收数据
// 接受原生JS Post过来的字段值 $user = isset($_POST['username']; $password = isset($_POST['password']); // 创建一个数组存放字段值 $data = array(); $data["username"] = $username; $data["password"] = $password; // 返回结果给JS $result = array("code"=>1,"msg"=>"OK!","data"=>$data); echo json_encode($result);