Ajax一直是Java前端中最受欢迎的技术之一,十分受程序员欢迎,但是ajax要如何编写呢,下面我们就来了解一下ajax的格式吧。
Ajax 是一种不需要刷新页面,也可以和服务端进行通信的方式。Ajax会向服务器发送异步请求,服务器返回部分数据,浏览器利用这些数据对当前页面局部更新;
ajax传输数据的3种方式:
1.XML:笨重,解析困难,但是XML是通用的数据交换格式
2.HTML:不用解析,可以直接放到文档中,但只更新一部分区域,并且传输数据也不方便,,且HTML代码需自己拼装
3.JSON: 小巧快捷,有面向对象特征,且很多第三方的jar包可以把java对象或集合装为JSON字符串
Ajax标准通用格式
$.ajax( { url: "http://www.test.com", //请求的url地址 dataType: "json", //返回格式为json async: true, //请求是否异步,默认为异步, data: { "id": "1" , "name": "名字" }, //参数值 type: "GET", //请求方式 beforeSend: function () { //请求前的处理 } , success: function (req) { //请求成功时处理 } , complete: function () { //请求完成的处理 } , error: function () { //请求出错处理 } });
例:
//发送ajax请求 $.ajax( { url: path + "/user/login.do" , type: "post" , data: { "name": name , "password": password } , dataType: "json" , success: function (result) { //result是服务器返回的JSON结 果 if (result.status == 0) { //将用户信息保存到Cookie var userId = result.data.cn_user_id; addCookie ("userId", userId, 2); window.location.href = "edit.html"; } else if (result.status == 1) { //用户名错 $("#count_span") .html(result.msg); } else if (result.status == 2) { $("#password_span") .html(result.msg); } } , error: function () { alert("登录失败!"); } });
Ajax请求格式
var rowsData = $('#receiptPrintList') .datagrid('getSelections'); $.ajax( { type: "post", url: "topupRecordController.do?updateReceiptInfo", data: { refNo: rowsData[0].refNo }, dataType: "json", success: function (result) {} }); //作用同上 $.post("topupRecordController.do?updateReceiptInfo" , { refNo: rowsData[0].refNo } , function (data) {}, "json");
以上就是本篇文章对ajax格式的解读了,更多Java入门知识请一直关注本网站吧。