我正在使用Codeigniter3和jQuery / Ajax创建一个图像上传器。
问题:我不明白如何找到我从ajax响应中得到的数组索引,如下所示。
以下是图片上传时的结果
{
"res": true,
"img_pro": {
"upload": {
"file_name": "web_page-_500_x_420px-06s1.png",
"file_type": "image\/png",
"file_path": "/uploads\/",
"full_path": "/uploads\/web_page-_500_x_420px-06s1.png",
"raw_name": "web_page-_500_x_420px-06s1",
"orig_name": "web_page-_500_x_420px-06s.png",
"client_name": "web_page-_500_x_420px-06s.png",
"file_ext": ".png",
"file_size": 233.79,
"is_image": true,
"image_width": 563,
"image_height": 420,
"image_type": "png",
"image_size_str": "width=\"563\" height=\"420\""
}
},
"token": "e291d9b7176d23647470083f7ccfd166"
}
我使用$.ajax
将图像发送到服务器
<script>
$(document).ready(function () {
$("#submit").on('click', function () {
$.ajax({
url: 'http://localhost/cootel/gotoadmin/image/upload',
type: 'POST',
data: new FormData($('#img_upload')[0]),
contentType: false,
cache: false,
dataType: 'json',
processData: false,
success: function (data) {
var items = [];
$.each(data, function (key, val) {
console.log(val.upload['file_name']);
if(val.upload.file_size ===2M){
alert("your file is 2M");
}
});
}
});
});
});
</script>
感谢您的帮助
答案 0 :(得分:2)
只需使用老式的方式..
success: function (data) {
var image;
if(!data.img_pro || !data.img_pro.upload) {
return;
}
image = data.img_pro.upload;
if(image.file_size > 2M) {
//Do something..
return;
}
..other checks..
}
答案 1 :(得分:0)
使用您为该功能指定的“key”参数(以及“val”参数): $ .each(data,function(key,val){
答案 2 :(得分:-1)
jQuery具有$.inArray()
方法,类似于JavaScript的indexOf()
方法。基本上,它在找不到任何索引时返回-1
。
例如:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery.inArray demo</title> <style> div { color: blue; } span { color: red; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <div>"John" found at <span></span></div> <div>4 found at <span></span></div> <div>"Karl" not found, so <span></span></div> <div>"Pete" is in the array, but not at or after index 2, so <span></span></div> <script> var arr = [ 4, "Pete", 8, "John" ]; var $spans = $( "span" ); $spans.eq( 0 ).text( jQuery.inArray( "John", arr ) ); $spans.eq( 1 ).text( jQuery.inArray( 4, arr ) ); $spans.eq( 2 ).text( jQuery.inArray( "Karl", arr ) ); $spans.eq( 3 ).text( jQuery.inArray( "Pete", arr, 2 ) ); </script> </body> </html>
(Source)
此示例来自jquery api website。