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