4002—Ajax随笔

8、getJSON的缓冲问题

     $.getJson()在IE浏览器中存在缓存问题,第二次request时,不会进入后台,而会访问缓存      

    有2种解决方法:

     8—1 改用Ajax语句

 

     8—2 增加携带的参数     

$.getJSON(
          "/Member/GetExercise.html", 
          { id: $("#Wareid").val(), isBool: loop, 
            random:Math.random()         //增加一个随机数
          }
, function (data) });

//第二种方法:
$.getJSON(
          "/Member/GetExercise.html?random=Math.random", 
          { id: $("#Wareid").val(),isBool: loop,
          }, 
          function (data) });

    

 

 

7、提交队列list数据到后端

        7—1  非json提交 

         前端JS         

var params = {  ids:[]  }
                 
$.each(selectedData, function (index, item) { 
    params.ids.push(item.value);
})

    $.ajax({
           type:'post',
           dataType:'json',
           url: '../MGR_Customer/setCustomerContact',
           data:params,
           traditional: true,
           success: function (jqXHR, status) {

           }, error: function (xhr) {
                            
           }
    });

         后端c#         

 [HttpPost]
 public JsonResult setCustomerContact(int[]  ids)
 {   
      LoginResultModel res = new LoginResultModel()
      {
           Success = isWork,
           Message = isWork ? responContent.ToString() : errContent.ToString()
       };

       return Json(res);
  }

      7—2  json提交 

      前端JS        

var ids = [];

$.each(selectedData, function (index, item) { ids[index]=item.value })

$.ajax({
        type:'post',
        dataType:'json',
        url: '../MGR_Customer/setCustomerContact',
        data:JSON.stringify( ids),                       
        contentType:'application/json',
        success: function (jqXHR, status) {

        }, error: function (xhr) {
                            
        }
});

         后端c#   

 [HttpPost]
 public JsonResult setCustomerContact(List<string>  ids)
 {
    
      return Json("");
 }

6、【AJAX】技术点 

       6—1 返回数据预处理        

$.ajax({
		url:'http://localhost:1497/api/User/getBusinessGroup',
		async:true,					
		method:'get',
		complete:function(jqXHR,textStatus){
						
			if(jqXHR.readyState==4){
				//返回类型为httpresponsemessage,需转换为JSON才能使用	
				var  list=JSON.parse(jqXHR.responseText);
				list.forEach(function(e,i){	
                    //只有数组,列表才能使用forEach,否则报错:forEach  is not function						
					console.log(i+"  index:"+e.Fid+" 编号:"+e.Fnumber+" 名称:"+e.Fname+"  特色:"+e.Fspec);
				});
			}											
		},error:function(xhr){
						
			alert(xhr);
		}					
});

 

 

 

 

5、【AJAX】返回数据到<table>

        C#代码如下      

 public class TestController : Controller
    {
        List<userModel> userList = new List<userModel>();        
        // GET: Test
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult List()
        {
            userList.Add(new userModel()
            {
                Name="贾志国",
                Age=41,
                Address="北京市东城区",
                Sex="男"
            });

            userList.Add(new userModel()
            {
                Name="和平",
                Age=39,
                Address="北京市东城区和平里街道",
                Sex="女",
            });

            userList.Add(new userModel()
            {
                Name="贾志新",
                Address="北京市东城区和平里街道",
                Age=32,
                Sex="男"
            });
                                                 
            AjaxEntity<List<userModel>> myResult = new AjaxEntity<List<userModel>>() { 
                
                Success=true,
                Message="成功啦",
                Data=userList
            };
            //—9—    返回JSON
            return Json(myResult, JsonRequestBehavior.AllowGet);
        }        
    }

Models内容 

 public class AjaxEntity<T>
    {
        [JsonProperty(PropertyName = "Success")]
        public bool Success { get; set; }

        [JsonProperty(PropertyName = "Message")]
        public string Message { get; set; }

        [JsonProperty(PropertyName = "Data")]
        public T Data { get; set; }
    }

Index.html

<!--  在body块内      -->
    <div id="header_field">
        
        <form id="form_field">
            <input type="button" id="btnGet" value="获取" />
        </form>
        <div id="data-result">
            <p id="result_title"><h4><b>获取内容:</b></h4></p><p id="result_message"></p>
            
            <table border="1px" cellpadding="0">
                <tr>
                    <th width="150">姓名</th>
                    <th width="100">性别</th>
                    <th width="100">年龄</th>
                    <th width="200">地址</th>
                </tr>
                <tbody id="tbody">
                </tbody>
            </table>
        </div>
    </div>

    <script type="text/javascript">
        $("#btnGet").click(function () {
            $.ajax(
                   {
                       type: 'get',
                       url: '/Test/List',                      
                       success: function (data, status, xhr) {
                           
                           if(status){
                           
                               $("#result_title").html("!");
                               var msg = data.Message;

                               if (data.Success) {
                                   
                                   $("#result_message").html("返回成功—"+msg);
                               } else {

                                   $("#result_message").html("返回失败—"+msg);
                               }
                               
                               var list = data.Data;
                               loadList(list);
                           }else{
                               
                               $("#result_title").html("F");
                           }

                       },
                       error: function (xhr) {
                           alert(xhr);
                       }
              }
            )
        });

        function loadList(list) {
            var tbody = $("#tbody");
            var html = "";
            //_2 遍历数据源
            list.forEach(function (e) {

                html += "<tr>";
                html += "<td>" + e["Name"] + "</td>"
                html += "<td>" + e["Sex"] + "</td>"
                html += "<td>" + e["Age"] + "</td>"
                html += "<td>" + e["Address"] + "</td>"

                html += "</tr>";
            });

            tbody.append(html);
        }

    </script>

效果如下:

4、【JQuery/JS】Ajax提交数据到actionResult

     4—1 action代码       

 [HttpPost]
 public ActionResult calculateJson()
 {
     var sr = new StreamReader(Request.InputStream);
     var stream = sr.ReadToEnd();

     var list = JsonConvert.DeserializeObject<List<userViewModel>>(stream);
     if(list.Any()){
            
                //判断有无数据
            }

            userModel newModel = new userModel()
            {
                Name=list[0].name,
                Age=1,
                Address="中国未定义 "+list[0].phone,
                Sex="未知"
            };

            AjaxEntity<userModel> myResult = new AjaxEntity<userModel>()
            {
                Success=true,
                Message="OK",
                Data=newModel
            };

            return Json(myResult);
}

     4—2 网页代码      

 $("#btnPost").click(function () {
            //—1—   initialize
            var txtname=$("#txtname").val();
            var txtphone=$("#txtphone").val();

            //声明一个JSON数组串
            var jsonPara = [];
            jsonPara.push({ "name": txtname, "phone": txtphone });

            //提交数据
            $.ajax(
                {
                    url:"/Test/calculateJson",
                    async:false,
                    type:'post',
                    dataType: 'json',
                    contentType:'application/json',
                    data: JSON.stringify(jsonPara),
                    success: function(data,status,xhr) {

                        if(status){
                        
                            var receiveTitle;
                            if(data.Success){
                                
                                receiveTitle = "1";
                                receiveTitle += data.Message + "--" + data.Data.Name;
                            }else{
                        
                                receiveTitle = "0";
                                receiveTitle += data.Message;
                            }

                            $("#txtphone").val(receiveTitle);

                        }else{
                
                            alert("接收失败");
                        }
                    },
                    error: function () {

                        alert("请求失败");
                    }
                }
            )

        });

1、JQuery【Ajax各种方式】异同 

      1—1   GET()    异步请求   

      格式:$.get( url [, data] [, callback] )

$.get(
    "/Test/showData",          //请求Url
    {
        id=33,name=tommas      //Data
    },
    function(data,state){
        //ajax请求成功后,执行
        
        alert(data)            //返回的数据
    }
)

      1—2   POST()   异步请求 

      格式:$.post(url,[data],[callback],[type])

$.post(

    "/Test/personal",             //访问Url
    {
        id=123,                   //传入参数
        name="ashly",
    },
    function(data,state){

        alert(data);            //返回数据结果
    },
    “json”                       //数据类型
)

     1—3  $.getJSON()     

      格式:getJSON(url,[data],[callback])  。支持跨域访问      

$.getJSON(
          "../MGR_Customer/getCustomerTypeList"
          , function (data,status) {
                //回调函数
                $.each(data, function (index,item) {
                    $("#qey-type").append(new Option(item.Fname, item.Fid))
                })
            }
);

     1—4  $.ajax()

     标准ajax函数。 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值