Ajax4 - 请求PHP接口

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Ajax4 - 请求PHP接口</title>
</head>
<body>
	<button id="button">获取PHP数据</button>
	<br><br>
	<h1>正常表单GET提交数据到PHP</h1>
	<form action="process.php" method="GET">
		<input type="text" name="name">
		<input type="submit" value="提交">
	</form>

	<h1>Ajax请求数据GET</h1>
	<form id="getForm">
		<input type="text" name="name" id="name1">
		<input type="submit" value="提交">
	</form>

	<h1>正常表单POST提交数据到PHP</h1>
	<form action="process.php" method="POST">
		<input type="text" name="name">
		<input type="submit" value="提交">
	</form>

	<h1>Ajax请求数据POST</h1>
	<form id="postForm">
		<input type="text" name="name" id="name2">
		<input type="submit" value="提交">
	</form>

	<script>
		document.getElementById('button').addEventListener('click',getData);
		document.getElementById('getForm').addEventListener('submit',getForm);
		document.getElementById('postForm').addEventListener('submit',postForm);

		function getData(){
			var xhr = new XMLHttpRequest();
			xhr.open('GET',"process.php?name=Henry",true);
			xhr.onload = function(){
				console.log(this.responseText);
			}
			xhr.send();
		}

		function getForm(e){
			e.preventDefault();
			var name = document.getElementById('name1').value;
			var xhr = new XMLHttpRequest();
			xhr.open('GET',"process.php?name="+name,true);
			xhr.onload = function(){
				console.log(this.responseText);
			}
			xhr.send();
		}

		function postForm(e){
			e.preventDefault();
			var name = document.getElementById('name2').value;
			var params = "name="+name;
			var xhr = new XMLHttpRequest();
			xhr.open('POST',"process.php",true);
			// 设置请求头
			xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
			xhr.onload = function(){
				console.log(this.responseText);
			}
			xhr.send(params);
		}
	</script>
</body>
</html>

process.php

<?php 
	
	# echo "Hello World!";

	if (isset($_GET['name'])) {
		echo "GET: 你的名字是". $_GET['name'];
	}

	# 连接数据库
	$conn = mysqli_connect("localhost","root",'','ajaxtest');

	if (isset($_POST['name'])) {
		// echo "POST: 你的名字是". $_POST['name'];

		# 将拿到的数据转化一下
		$name = mysqli_real_escape_string($conn,$_POST['name']);

		$query = "INSERT INTO users(name) VALUES('$name')";
		mysqli_query($conn,"set name utf8");
		if(mysqli_query($conn,$query)){
			echo '用户添加成功!';
		}else{
			echo "用户添加失败!".mysqli_error($conn);
		}
	}
?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值