zoukankan      html  css  js  c++  java
  • Ajax发送FormData对象封装的表单数据

    前端页面:

    <!doctype html>
    <html lang="en">
     <head>
      <meta charset="UTF-8">
      <meta name="Generator" content="EditPlus®">
      <meta name="Author" content="">
      <meta name="Keywords" content="">
      <meta name="Description" content="">
      <title>formdata对象封装表单数据</title>
    <script type="text/javaScript">
    
    function send(){
    	var xhr=new XMLHttpRequest();
    	xhr.open('POST','./01.php',true);//异步传输
    	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    	var fm=document.getElementsByTagName('form')[0];
    	var fd=new FormData(fm);
    	xhr.onreadystatechange=function(){
    		if(this.readyState==4){
    			document.getElementById('username').innerHTML=xhr.responseText;
    		}
    	}
    	fd.append('act','zhuce');
    	xhr.send(fd);
    
    }
    </script>
     </head>
     <body>
    	<form action="./01.php" method="post">
    		<p>用户名:<input type="text" name="username"/><span id="username"></span></p>
    		<p>密码:<input type="password" name="pwd"/></p>
    		<p>邮箱地址:<input type="text" name="eamil"/></p>
    		<input type="button" value="注册" onclick="send()">
    	</form>
     </body>
    </html>
    

     php接收页面

    <?php
    print_r($_POST);
    $name=Array('test111','admin','Admin');
    if(isset($_POST)){
    	if(in_array($_POST['username'],$name)){
    		echo '用户名已经注册';
    	}else{
    		echo '可以注册';
    	}
    }
    ?>
    

     出现以下错误

    解决办法

    将XMLHTTPRequest对象设置的头信息
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    删掉或注释就可以了
    

     

  • 相关阅读:
    重构29-Remove Middle Man(去掉中间人)
    重构30-Return ASAP(尽快返回)
    重构26-Remove Double Negative(去掉双重否定)
    yaml语法学习3
    运行原理探究2
    SpringBoot简介 1
    SpringMVC项目所引用的一切依赖jar包和自定义设置
    2020/07/03 初始mybatis
    json数据格式字符串在java中的转移
    项目中遇到的一些异常
  • 原文地址:https://www.cnblogs.com/lzzhuany/p/4869332.html
Copyright © 2011-2022 走看看