<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<title>新建网页</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<script type="text/javascript">
function checkname(){
//ajax校验用户名
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
document.getElementById('result').innerHTML = xhr.responseText;
xhr.open('post','./05.php?height=165'); //url中传递get参数。
//post请求需要把数据组织为xml格式
//以下方法必须要在"open"方法后进行设置
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); //post传递参数必须设置该form表单项(以xml的表单形式传递参数)
//获得输入的用户名,并传递个服务器端
var ming = document.getElementById('username').value;
//对ming变量的特殊符号(&、=)信息进行编码
ming = encodeURIComponent(ming);
//把传递的参数变为"请求字符串"传递给send方法
var info = "nm="+ming+"&age=20";
xhr.send(info); //send()函数 传递post参数(可以即通过url传递get参数,又通过send传递post参数)
</script>
</head>
<h2>ajax之post形式请求</h2>
<p>用户名:<input type="text" id="username" οnblur="checkname()" /></p>
<p>密码:<input type="password" id="userpwd" /></p>
<div id="result"></div>
</body>
</html>
05.php:
//服务器端校验用户名
$exists = array('linken','mary','jim');
echo "post:";
print_r($_POST);
echo "get:";
print_r($_GET);
exit;
$name = $_POST['nm'];
//判断用户名是否存在
if(in_array($name,$exists)){
echo "<span style='color:red'>用户名已经存在,请换一个</span>";
}else{
echo "<span style='color:green'>恭喜,可以使用此名字</span>";
新建网页 function checkname(){ //ajax校验用户名 var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){
1.创建
XMLHttpRequest
对象
let xhr = new
XMLHttpRequest
();
2.建立对服务器的调用。第一个参数是对GET或者
POST
, 第二个参数可以是相对或者绝对路径, 第三个参数: true异步/false同步, 默认为true
xhr.open("
POST
", "/upimage", true);
3.向服务器发送
请求
, 仅用于
post
xhr.send(formData);
4.服务器的响应,表示一个串
xhr.responseText;
POST
请求
的适用性更广,可使用更大的
请求
参数,而且
POST
请求
的
请求
参数通常不能直接看到。因此在使用
Ajax
发送
请求
时,尽量采用
POST
方式而不是GET方式发送
请求
。发送
POST
请求
通常需要如下的三个步骤:
1) 使用open方法打开连接时,指定使用
POST
方式发送
请求
。
2) 设置正确的
请求
头,
POST
请求
通常应设置Content-Type
请求
头
使用
XMLHttpRequest
时,直接在send 函数中写字符串,和 使用formData是不用的
function send(userid,name,node,href,asyn) {
var xmlhttp=new
XMLHttpRequest
();
var url=url_ban;
////直接send字符串或者json串
//var conte...
原生JS的异步
POST
请求
回调代码如下:
function test(url, param, callback) {
var xmlhttp = new
XMLHttpRequest
();
xmlhttp.open("
POST
", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/json;c...
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
//
请求
成功
5. 发送
请求
xhr.send('your_data');
注意,如果要发送的数据是表单数据,需要使用 `URLEncoder.encode` 方法将表单数据编码。
xhr.send(URLEncoder.encode('form_data', 'UTF-8'));
希望这些内容能够帮到你。