ajax 异步提交数据、文件和跨域提交的实现

来源:互联网 发布:java 高并发http接口 编辑:程序博客网 时间:2024/06/03 16:01

在网站中经常需要无刷新提交数据,或者上传图片的情况,还有就是跨域提交的情况,现记录下自己的总结,以待后续。

首先是需要引用jquery.js   建议使用较高的版本,不然会不支持上传图片。http://code.jquery.com/jquery-1.9.0.js

1.异步提交数据:

function getAjax(){

$.ajax({
type : "get",
dataType : "json",
url : "/news/detail.html",
data : {

id : 1

},
complete : function() {
},
success : function(result) {
var data = result['success'];
alert(result['msg']);
},
});

}

2,异步上传图片:

function uploadImg() {
var data = new FormData();
data.append('upfile', $('#uploadfile')[0].files[0]);
$.ajax({
url : '/upload/img',
type : 'POST',
dataType : "JSON",
data : data,
processData : false, // 告诉jQuery不要去处理发送的数据  
contentType : false // 告诉jQuery不要去设置Content-Type请求头  
}).done(function(data) {
var ret = data['state'];
});
}

3,跨域提交或查询

function getAjax(){

$.ajax({
type : "get",
dataType : "jsonp",
url : "/news/detail.html",
data : {

id : 1

},
complete : function() {
},
success : function(result) {
var data = result['success'];
alert(result['msg']);
},
});

}

记录开发过程中的点滴!
0 0
原创粉丝点击