Ajax与Gson

1. ajax的底层操作方法:

 

代码get请求 

 

             Get请求

  

2. Post请求

 

 

      $("#chufa").click(function () {
          var val  = $("#search");
          var value = val.val();
         var xhr1 ;
         if (XMLHttpRequest){
           xhr1 =   new XMLHttpRequest();
           xhr1.open('post','hello2');
           /*设置一个请求头*/
             xhr1.setRequestHeader('Content-type','application/x-www-form-urlencoded');
           xhr1.send('name='+value);
           xhr1.onreadystatechange  =function () {
               if (xhr1.status == 200 && xhr1.readyState ==4){
                   var txt = xhr1.responseText;
                   $("#mytable").css("display","")
               }


           }
         }
      });
post请求代码

3. 使用Gson 代码

      Gson 代码的依赖  
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency>

使用Gson 传送集合

 前台接收数据

 

 $("#tijiao").click(function () {

        var xhr ;
        if (XMLHttpRequest){
            xhr = new XMLHttpRequest();

            xhr.open("post","hello2");
            xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
            xhr.send('name=zhangsan');
            //响应结果
            xhr.onreadystatechange = function () {
                if (xhr.status == 200 && xhr.readyState ==4){
                    var txt = xhr.responseText;
                   var obj1 =  JSON.parse(txt);
                    for (var i=0; i<obj1.length;i++) {
                       var x = console.log(obj1[i]);
                       var id = obj1[i].id;
                        var name = obj1[i].name
                        var category = obj1[i].category
                        $("#mytd").append($('<tr>'+
                            '<td>'+id+'</td>'+
                            '<td>'+name+'</td>'+
                            '<td>'+category+'</td>'+
                            '</tr>'));
                    }   }

                }
            }

  })
    //    $("#mytd")

    })
代码

 

 

 

 

 

猜你喜欢

转载自www.cnblogs.com/zhulina-917/p/11754003.html