form表单与ajax的区别

form表单

1.概念

  • 是在浏览器端发起的同步请求
  • 整个页面一起刷新

2.示例

  • action指明要提交到的url,method为提交方法,为post或是get。
  • 如果方法为get,表单提交的数据会被写在请求头的URL里(请求头里没有Content-type字段);
  • 如果方法为post,数据会被保存在请求体里,请求头的Content-type字段的值是application/x-www-form-urlencoded。
  • 表单每次提交都会导致页面刷新。点击会提交表单内容的,有三个标签:
 
 
 

ajax

1.概念

  • 是js中发起异步请求的机制
  • 整个页面的局部刷新

2.请求方式

GET请求方式

  • 示例
              $('#btn').click(function () {
                    var param = {
                       kind: 1
                    }
                    $.ajax({
                        type:'get',
                        url:'http://192.168.35.66:5000/get_movie_list',
                        data :param,
                        success:function(response){
                            //    console.log(response)
                            //    console.log(typeof(response))
                            // console.log(response.movie_list)

                            // 清空列表数据
                            $('#ul2').html('')
                            // 遍历字典数据并添加到列表中
                            for (var i = 0;i"+response.movie_list[i]+"")
                            }

                        },
                        error:function(error){  // 请求失败的回调  error是错误信息
                             console.log(error)
                            // console.log(typeof(error))
                        }
                    })

POST请求方式

(1)post-form(用户登录)–键值对数据

           // ajax发起post请求 发送键值对数据, 和原生form发送数据一样
           var param = {
               username :'zhangsan',  // 登录成功
            //    username :'ls',  // 用户名/密码错误
               password:'123456'
           }
            $.ajax({
                type:'post',
                url:'http://192.168.35.66:5000/login',
                data:param,
                success:function(response){
                    console.log(response)
                    console.log(typeof(response))  // js对象--object类型
                    
                },
                error:function (error) {
                    alert('请求失败')
                }
            })

(2)post-json(接口功能–添加数据内容)–纯文本数据

            // ajax发起post请求, 发送文本数据(json字符串)
            var param ={
                    movie_name:'大话西游',
                    movie_comment:'一生所爱'
            }       
            $.ajax({
                type:'post',
                url:'http://192.168.35.66:5000/add_movie_comment',
                data:JSON.stringify(param), // json对象--->js对象
                contentType:'application/json',
                success:function(response){
                    console.log(response)
                    console.log(typeof(response))
                },
                error:function (error) {
                    alert('请求失败')
                }
            })

(3)post-文件(接口功能–上传图片文件)–文件数据

    
    
    

备注:

你可能感兴趣的:(form表单与ajax的区别)