ajax小应用

1.ajax提交表单

HTML

<form action="#" id="form1">
	<input type="text" name="username" id="username" />
	<input type="password" name="password" id="password" />
	<input type="submit" value="提交" name="submit"/>
</form>

JS

var f1=document.getElementById("form1");

f1.onsubmit=function(){
	var xhr = new XMLHttpRequest();
	
	xhr.open('get','getList.php?username='+f1.username.value+'&password='+f1.password.value,true);
	
	xhr.onload=function(){
		alert(xhr.responseText);
	}
	xhr.send();
	return false;
}

PHP

<?php
header('Content-type:text/html;charset="utf-8"');
error_reporting(0);

$username = $_GET['username'];
$password = $_GET['password'];

echo "你提交的数据是 username : {$username},password : {$password}";

2.ajax上传文件限制大小

HTML

<input type="file" id="file" />

JS

var file1=document.getElementById("file");

file1.onchange=function(){
	var files = this.files;
	
	//判断是否选择文件
	if(files.length==0)return;
	
	//判断文件大小是否超出50M
	if(files[0].size>52428800){
		alert('你要上传的文件超出了限制');
		return;
	}
	
	var xhr=new XMLHttpRequest();
	xhr.open('post','getList.php',true);
	
	xhr.onload=function(){
		alert(xhr.responseText);
	}
	
	//处理需要上传的文件
	var fd=new FormData();
	fd.append('file',files[0]);
	//上传
	xhr.send(fd);
}

PHP

<?php
header('Content-type:text/html;charset="utf-8"');
error_reporting(0);

$username = $_GET['username'];
$password = $_GET['password'];
<?php
header('Content-type:text/html; charset="utf-8"');
$upload_dir = 'uploads/';

if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
	exit_status(array('code'=>1,'msg'=>'错误提交方式'));
}

if(array_key_exists('file',$_FILES) && $_FILES['file']['error'] == 0 ){
	
	$pic = $_FILES['file'];
	
	if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
		exit_status(array(
            'code'=>0,
            'msg'=>'上传成功',
            'url'=>$upload_dir.$pic['name'],
            'name'=>$pic['name']
		));
	}
	
}
echo $_FILES['file']['error'];
exit_status(array('code'=>1,'msg'=>'出现了一些错误'));

function exit_status($str){
	echo json_encode($str);
	exit;
}
?>

  

 

posted @ 2018-01-09 14:23  carol72  阅读(151)  评论(0编辑  收藏  举报