post request of Ajax

There are four points to pay attention to in ajax get requests:

  1. Passing data to the server requires a call to the send (request string data) method
  2. Call the setRequestHeader() method to organize the passed data into xml format (passing the data by imitating the form form)
  3. The transmitted Chinese information does not need to be encoded, and special symbols such as &, = still need to be encoded
  4. In this way, GET parameter information can be passed at the same time as the request, and the information can also be received by $

ajax initiates post request

Server 03.php:

<?php

//Receive the "user name" information transmitted by post mode, and do database verification
echo "post:";
print_r($_POST);

echo "get:";
print_r($_GET);

Client 03post.html:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>ajax-get request</title>
	<script type="text/javascript">
	function checkname(){
		//ajax user name verification
		//Step 1: get user name information
		var nm = document.getElementById('username').value;

		//Code special symbols (such as &, = etc.) passed
		//At the same time, Chinese is also encoded
		 nm = encodeURIComponent(nm);

		//Change user name information to "request string"
		var info = "name="+nm+"&age=23";

		//Step 2: ajax verification
		var xhr = new XMLHttpRequest();
		//ajax event settings to receive the returned information
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4){
				alert(xhr.responseText);
			}
		}
		xhr.open('post', './03.php?addr=beijing');//get parameter information added
		//post mode is to simulate form form form to transfer data
		//The post format data of form is passed to the server through xml
		//The following setRequestHeader() method must be invoked after the open() method.
		xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
		xhr.send(info);
	}
	</script>
</head>
<body>
	<h2>ajax Verification of user name( post Mode)</h2>
	<p>User name:<input type="text" id="username" onblur="checkname()"></p>
	<p>phone number:<input type="text" id="usertel"></p>
</body>
</html>

Note:

The post mode request needs to organize the information as a request string and pass it to the send() method:

For post mode requests, header header protocol needs to be set to organize data into xml format:

Flag to pass post form information in xml format:


The post request can also pass the get parameter information, which can also be received using $


Tags: xml PHP Database Javascript

Posted on Sat, 15 Feb 2020 08:25:21 -0800 by jon2s