Submit form via ajax form data in several ways

A, FormData method

effect:
  1. Analog HTML form is equivalent to mapping the HTML form to the form object, the data form object automatically spliced ​​into the format of request parameters.
  2. Asynchronous upload binary files
use
  • Use of native ajax

    
    <form id="form"> 
        <input type="text" name="username" /> 
        <input type="password" name="password" /> 
        <input type="button"/> 
    </form>
    
    
      var form = document.getElementById('form'); 
      // 将html表单转换为formData表单对象
      var formData = new FormData(form );
      // 创建ajax对象
      var xhr = new XMLHttpRequest();
      // 对ajax对象进行配置
      xhr.open('post', 'http://localhost:3001/login');
      // 当发送跨域请求时,携带cookie信息
      xhr.withCredentials = true;
      // 发送请求并传递请求参数
      xhr.send(formData);
      // 监听服务器端给予的响应内容
      xhr.onload = function () {
      	console.log(xhr.responseText);
      }
    

    Service-Terminal:

    app.post('/login', (req, res) => {
      // 创建表单解析对象
      var form = formidable.IncomingForm();
      // 解析表单
      form.parse(req, (err, fields, file) => {
      	// 接收客户端传递过来的用户名和密码
      	const { username, password } = fields;
      	// 用户名密码比对
      	if (username == 'test' && password == '123456') {
      		// 设置session
      		req.session.isLogin = true;
      		res.send({message: '登录成功'});
      	} else {
      		req.session.isLogin = false;
      		res.send({message: '登录失败, 用户名或密码错误'});
      	}
      	})
      })
    

    note:

    • Formdata get request object can not be used, because the object needs to be passed to the send process, the get request and the request parameters embodiment only on the back of the request address.
    • BodyParser server module can not be resolved formData form data objects, we need to use the formidable module for resolution.
  • Use of jquery

    
    <form id="form"> 
        <input type="text" name="username" /> 
        <input type="password" name="password" /> 
        <input type="button"/> 
    </form>
    
    
      let form = document.querySelector('#form');
      $.ajax({
      	type:"post",
      	url:"/login",
      	data:formData,
      	success:function(res){
      	},
      	processData: false,
      	contentType: false,
      	error:function(xhr){
      		console.log(xhr)
      	}
      })
    

    Service-Terminal:

    app.post('/login', (req, res) => {
      // 创建表单解析对象
      var form = formidable.IncomingForm();
      // 解析表单
      form.parse(req, (err, fields, file) => {
      	// 接收客户端传递过来的用户名和密码
      	const { username, password } = fields;
      	// 用户名密码比对
      	if (username == 'test' && password == '123456') {
      		// 设置session
      		req.session.isLogin = true;
      		res.send({message: '登录成功'});
      	} else {
      		req.session.isLogin = false;
      		res.send({message: '登录失败, 用户名或密码错误'});
      	}
      	})
      })
    

Two, SerializeArray method

effect:
  1. The data is automatically spliced ​​to form theAn array
use
  • Use of native ajax(Json format data transmission)
     <form id="form"> 
      <input type="text" name="username" /> 
      <input type="password" name="password" /> 
      <input type="submit"/> 
     </form>
    
      function serialize2Json(form) {
          var result = {};
          // [{name: 'email', value: '用户输入的内容'}]
          var f = form.serializeArray();
          f.forEach(function(item) {
              // result.email
              result[item.name] = item.value;
          });
          return result;
      }
      $('#form').on('submit', function() {
        let result = serialize2Json($(this)); //将表单数据转为json格式的数据
        // 创建ajax对象
      	var xhr = new XMLHttpRequest();
      	// 对ajax对象进行配置
      	xhr.open('post', 'http://localhost:3001/json');
      	// 当发送跨域请求时,携带cookie信息
      	xhr.withCredentials = true;
      	// 设置请求参数格式的类型(post请求必须要设置)
      	xhr.setRequestHeader('Content-Type', 'application/json');
      	// 发送请求并传递请求参数
      	xhr.send(JSON.stringify(result ));// 将json对象转换为json字符串发送
      	// 监听服务器端给予的响应内容
      	xhr.onload = function () {
      		console.log(xhr.responseText);
      	}
         // return false//默认阻止提交数据跳转
     })
    
    Service-Terminal:
    	app.post('/json', (req, res) => {
    		res.send(req.body);
    	});
    
  • Use of jquery(Json format data transmission)
     <form id="form"> 
      <input type="text" name="username" /> 
      <input type="password" name="password" /> 
      <input type="submit"/> 
     </form>
    
      // 将表单中用户输入的内容转换为对象类型  
      function serializeObject (obj) {   
      	// 处理结果对象   
      	var result = {};   
      	// [{name: 'username', value: '用户输入的内容'}, {name: 'password' , value: '123456'}]   
      	var params = obj.serializeArray();   
      	// 循环数组 将数组转换为对象类型   
      	$.each(params, function (index, value) {   
      	 result[value.name] = value.value;   
      	 })   
      	 // 将处理的结果返回到函数外部   
      	 return result;  
       }
      $('#form').on('submit', function() {
      	  //将表单数据转为json格式的数据
          let result = serialize2Json($(this)); 
          $.ajax({
      		type:"post",
      		url:"/json",
      		// 向服务器端发送的请求参数
      		// name=zhangsan&age=100
      		// data: {
      		// 	name: 'zhangsan',
      		// 	age: 100
      		// },
      		data: JSON.stringify(result),
      		// 指定参数的格式类型
      		contentType: 'application/json',
      		success:function(res){
      			
      		},
      		error:function(xhr){
      			console.log(xhr)
      		}
      	})
         // return false//默认阻止提交数据跳转
     })
    
    Service-Terminal:
    	app.post('/json', (req, res) => {
    		res.send(req.body);
    	});
    

Three, Serialize method

effect:
  1. The data is automatically spliced ​​to form theString typeParameters
    Note :( Parameter name = & Parameter Name Parameter Value Parameter Value =)
use
  • Use of native ajax
     <form id="form"> 
      <input type="text" name="username" /> 
      <input type="password" name="password" /> 
      <input type="submit"/> 
     </form>
    
    post request method
      $('#form').on('submit', function() {
      	var params = $('#form').serialize();// username=''&age=''
      	// 创建ajax对象
      	var xhr = new XMLHttpRequest();
      	// 对ajax对象进行配置
      	xhr.open('post', '/test');
      	// 当发送跨域请求时,携带cookie信息
      	xhr.withCredentials = true;
      	// 设置请求参数格式的类型(post请求必须要设置)
      	xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      	// 发送请求并传递请求参数
      	xhr.send(params);// 
      	// 监听服务器端给予的响应内容
      	xhr.onload = function () {
      		console.log(xhr.responseText);
      	}
         // return false//默认阻止提交数据跳转
     })
    
    Service-Terminal:
    	app.post('/test', (req, res) => {
    		res.send(req.body);
    	});
    
    get request method
      $('#form').on('submit', function() {
      	var params = $('#form').serialize();// username=''&age=''
      	// 创建ajax对象
      	var xhr = new XMLHttpRequest();
      	// 对ajax对象进行配置
      	xhr.open('get', 'http://localhost:3001/test?'+params);
      	// 当发送跨域请求时,携带cookie信息
      	xhr.withCredentials = true;
      	// 发送请求并传递请求参数
      	xhr.send();// 
      	// 监听服务器端给予的响应内容
      	xhr.onload = function () {
      		console.log(xhr.responseText);
      	}
         // return false//默认阻止提交数据跳转
     })
    
    Service-Terminal:
    	app.get('/test', (req, res) => {
    		res.send(req.query);
    	});
    
  • Use of jquery
     <form id="form"> 
      <input type="text" name="username" /> 
      <input type="password" name="password" /> 
      <input type="submit"/> 
     </form>
    
    post request method
      $('#form').on('submit', function() {
      	  //将表单数据转为json格式的数据
          var params = $('#form').serialize(); 
          $.ajax({
      		type:"post",
      		url:"/test",
      		data:params,
      		// 指定参数的格式类型
      		contentType: 'application/x-www-form-urlencoded',
      		success:function(res){
      			console.log(res)
      		},
      		error:function(xhr){
      			console.log(xhr)
      		}
      	 })
         // return false//默认阻止提交数据跳转
     })
    
    Service-Terminal:
    	app.post('/test', (req, res) => {
    		res.send(req.body);
    	});
    
    get request method
      $('#form').on('submit', function() {
      	  //将表单数据转为json格式的数据
          var params = $('#form').serialize(); 
          $.ajax({
      		type:"get",
      		url:"/test",
      		data:params,
      		success:function(res){
      			console.log(res)
      		},
      		error:function(xhr){
      			console.log(xhr)
      		}
      	 })
         // return false//默认阻止提交数据跳转
     })
    
    Service-Terminal:
    	app.get('/test', (req, res) => {
    		res.send(req.query);
    	});
    
Published 84 original articles · won praise 11 · views 10000 +

Guess you like

Origin blog.csdn.net/chenshanqiang/article/details/103934308