Java 之 Web前端(六)

时间:2023-12-13 12:26:32

1.AJAX

  a.定义:异步的 JS 和 XML

  b.作用:不重新加载页面的情况下,与服务器的数据进行交互,改变网页的部分内容

  c.语法:

<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("../ajax/test1.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
});
}
</script>
</head>
<body> <div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction()">通过 AJAX 改变内容</button> </body>
</html>

2.JQuery—AJAX

  a.get方法

//$.get(URL,data,callback)

$.get("servlet/RegisterServlet",{userName:userName},function(result){
alert(result);
$("#msg").html(result);
})

  b.post方法(类似get方法)

//$.post(URL,data,callback)

  c.ajax方法

$.ajax({
url:"",
data:{},
dataType:"json",
success:function(){},
error:function(){},
})

3.JSON

  a.定义:JS对象表示法

  b.作用:存储和交换文本信息

  c.声明:

//产生JSONObject对象

//方法一
JSONObject obj = JSONObject.fromObject(user); //方法二
JSONObject obj = new JSONObject();
obj.accumulate("name",'zhangsan");
//当键相同时,自动构建数组

//产生JSONArray对象
JSONArray array = JSONArray.fromObject(users);