前端重新学习(15)javascipt之ajax代码实例(4)

Ajax请求PHP接口  获取php接口数据,以及利用get 、post向向数据库写入数据

自己写接口接收数据

 首先向后台服务器发送数据       

以下为html代码

ajax4.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Ajax 4 - 请求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="提交">
		<p>数据提交后会显示在链接中</p>
	</form>

	<h1>Ajax请求数据GET</h1>
	<form id="getForm">
		<input type="text" name="name" id="name1">
		<input type="submit" value="提交">
		<p>数据提交后不会显示在链接中</p>
	</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);//表单使用submit事件
		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;
			alert("params:"+params);
			var xhr = new XMLHttpRequest();
			xhr.open('POST',"process.php",true);
			// 设置请求头为POST
			xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
			xhr.onload = function(){
				console.log(this.responseText);
			}
			xhr.send(params);//post会利用send将数据传递回后台,所以要先组装好数据
		}	
			
	</script>
</body>
</html>

以上代码对应php代码process.php  请注意修改数据库密码,

<?php 	
	# echo "Hello World!";
	if (isset($_GET['name'])) {//将获取的参数返回
		echo "GET: 你的名字是". $_GET['name'];
	}
	# 连接数据库
	$conn = mysqli_connect("localhost","root",'20152832','demodb');

	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);
		}
	}
?>

向服务器请求数据,

首先需要服务器端打包好json数据

以下为users.php

<?php 
//php接口
	$conn =  mysqli_connect("localhost","root",'20152832','demodb');

	$query = 'SELECT * FROM users';

	$result = mysqli_query($conn,$query);

	$users = mysqli_fetch_all($result,MYSQLI_ASSOC);

	echo json_encode($users);//输出为json格式
 ?>

以下为对应的html前端代码

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Ajax 5 - 请求PHP数据</title>
</head>
<body>
	<button id="button2">请求所有用户</button>
	<br><br>

	<h1>所有用户</h1>
	<div id="users"></div>
	<script>
		document.getElementById('button2').addEventListener('click',loadUsers);
		function loadUsers(){
			var xhr = new XMLHttpRequest();
			xhr.open("GET","users.php",true);
			xhr.onload = function(){
				if (this.status == 200) {
					var users = JSON.parse(this.responseText);
					var output = '';

					// 遍历数组
					for(var i in users){
						output += 
							'<ul>'+
								'<li>'+users[i].id+'</li>'+
								'<li>'+users[i].name+'</li>'+
							'</ul>';
						;
					}
					document.getElementById('users').innerHTML = output;
				}
			}
			xhr.send();
		}
	</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_16546829/article/details/81746882
今日推荐