jquery怎么跟ajax添加图片
时间: 2023-11-25 12:50:43 浏览: 49
以下是使用jQuery和Ajax添加图片的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>jQuery Ajax上传图片</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#upload").click(function(){
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function(){
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
var position = event.loaded || event.position; var total = event.total;
if(event.lengthComputable){
percent = Math.ceil(position / total * 100);
}
$('#progressBar').css('width', percent + '%');
$('#progressBar').html(percent + '%');
}, true);
}
return xhr;
},
success: function(response){
alert(response);
}
});
});
});
</script>
</head>
<body>
<input type="file" id="file" name="file" />
<button id="upload">上传</button>
<div id="progressBar"></div>
</body>
</html>
```
在这个示例中,我们使用了jQuery的`$.ajax()`方法来发送POST请求。我们创建了一个FormData对象,并将文件添加到其中。我们还设置了`processData`和`contentType`选项,以确保jQuery不会将数据序列化为查询字符串,并设置正确的Content-Type头。
我们还使用了`xhr`选项来获取XMLHttpRequest对象,并添加了一个事件监听器来跟踪上传进度。最后,我们在成功回调函数中显示了响应。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)