先谈JavaScript的ajax,传输数据为json
#############################################JavaScript ajax json###########################################
注意:由于要用到json的JSON.stringify()方法,需要引入json2.js库。
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css" media="screen">
div {
width: 300px;
margin: 0 auto;
text-align: center;
border: 1px solid #ED7AE0;
border-radius: 4px;
padding: 15px;
}
input {
margin: 0 auto;
display: block;
margin-top: 15px;
width: 150px;
border-radius: 5px;
height: 24px;
border: 1px solid #40F3E6;
}
</style>
<script src="json2.js"></script>
<script src="index.js" defer="defer"></script>
</head>
<body>
<div>
<input type="text" required="true" name="" id="un"
placeholder="UserName" />
<input type="text" required="true" name="" id="pw" placeholder="Password" />
<input type="submit" name="" value="submit" id="sb" />
</div>
</body>
</html>
index.js
window.onload = function(){
(document.getElementById("sb")).onclick = function(){
var url = "" //填入后台文件路径
var data = {
userName : document.getElementById("un").value,
password : document.getElementById("pw").value
}
var jsonData = JSON.stringify(data); //将data对象转换为json字符串
ajax(url, jsonData);
}
}
function ajax(url, data) {
var oajax = null;
try{
oajax = new XMLHttpRequest();
}catch(xhrError){
alert("your brower isn‘t supporting XMLHttpRequest!");
}
try{
oajax = new ActiveXObject("Microsoft.XMLHTTP");
}catch(activeError_Microsoft_XMLHTTP){
alert("your brower isn‘t supporting ActiveXObject!");
}
oajax.open("POST", url, true);
oajax.send(data);
oajax.onreadystatechange = function(){
if(oajax.readyState == 4) {
if(oajax.status == 200) {
//后台返回数据操控view层
}
}
}
}
##########################################jQuery ajax json################################################
引入jQuery库和json2.js
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css" media="screen">
div {
width: 300px;
margin: 0 auto;
text-align: center;
border: 1px solid #ED7AE0;
border-radius: 4px;
padding: 15px;
}
input {
margin: 0 auto;
display: block;
margin-top: 15px;
width: 150px;
border-radius: 5px;
height: 24px;
border: 1px solid #40F3E6;
}
</style>
<script src="json2.js"></script>
<script src="index.js" defer="defer"></script>
</head>
<body>
<div>
<input type="text" required="true" name="" id="un"
placeholder="UserName" />
<input type="text" required="true" name="" id="pw" placeholder="Password" />
<input type="submit" name="" value="submit" id="sb" />
</div>
</body>
</html>
test.js代码:
$(document).ready(function(){
$("#sb").click(function(){
var route = ""; //数据传输到文件
var $content = {
userName: $("#un").val(),
password: $("#pw").val()
}
var content = JSON.stringify($content);
alert(content);
$.ajax({
type: "POST",
url: route,
data: content,
dataType: ‘json‘,
success:function(data){
}
});
});
});