记录一下Javascript原生post请求写法

原文地址:http://lsy.deld.vip/article/show/25.html

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);
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐