JavaScript教程

javascript中{},[]中括号,大括号区别

{} 大括号,表示一个对象,大部分情况下要有成对的属性和值,或是函数

1
var jason = {"name" : "Jason", "age" : 18};

访问方式有jason.name,jason["name"]

1
2
3
4
5
6
7
8
var jason = {
name = function() {
return "jason";
},
age = function() {
return 18;
}
};

访问方式jason.name()

[]中括号,表示一个数组,也可以理解为一个数组对象

1
var jason = ["name" , "Jason", "age" , 18];

访问方式jason[0]

可以结合使用,通过下标访问

1
2
3
4
var jason = {
"name" , "Jason", "age" , 18,
"myCar" : [{"name" : "black Car"}]
};

访问jason.myCar[0].name

JavaScript动态增加属性

1
2
3
4
5
6
7
8
9
var obj = {};

obj.name = "Lily";
obj.age = 18;

var key = "addr";//key 还可以是数字或者对象
var value = "china";
obj[key] = value;
console.log(obj)

文件上传

FormData

通过ajax实现,优先使用的方法

1
2
3
4
5
6
7
8
9
<form enctype="multipart/form-data" method="post" name="fileinfo">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" /><br />
<label>File to stash:</label>
<input type="file" name="file" required />
<input type="submit" value="Stash the file!" />
</form>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {

var oOutput = document.querySelector("div"),
oData = new FormData(form);

oData.append("CustomField", "This is some extra data");

var oReq = new XMLHttpRequest();
oReq.open("POST", "stash.cgi", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
} else {
oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>";
}
};

oReq.send(oData);
ev.preventDefault();
}, false);

Jquery ajaxSubmit

次选

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(function(){   
var options = {
type: 'POST',
url: 'stash.cgi',
success: showResult, // 回调函数
dataType: 'json', // 返回信息格式
error : function(xhr, status, err) {
alert("操作失败");
}
};
$("#test").submit(function(){
$(this).ajaxSubmit(options);
return false; // 防止表单自动提交
});
});