我使用AJAX
在我的表单中将图片发布到数组中,作为回应,我收到了JSON
数据
我在控制台中收到以下代码作为回复;
0"C:\xampp\htdocs\3Dklik\..../1492427792slider_7.jpg"
1"C:\xampp\htdocs\3Dklik\mog/1492427792slider_2.jpg"
2"C:\xampp\htdocs\3Dklik\mo…../public/img/1492427792"
id""
user_id"1"
以下是我的AJAX
代码:
<script type="text/javascript">
$(document).ready(function(e) {
$("#btnsubmit").on('click', function(e) {
e.preventDefault();
var formData = $('#uploadform').serialize();
var files = $("#uploadform")[0];
console.log(files);
$.ajax({
url: '<?php echo $this->url('
upload ');?>',
type: 'POST',
data: new FormData(files),
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data) {
alert("Data Uploaded: " + data);
console.log(data);
},
error: function(result) {
alert("Error");
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
</script>
以下是我的PHP
代码;
public function uploadAction() {
$request = $this - > getRequest();
if ($request - > isPost()) {
$data = array_merge_recursive(
$request - > getPost() - > toArray(),
$request - > getFiles() - > toArray()
);
// echo'<pre>';print_r($data);
}
$image_array = array_slice($data, 2);
//print_r($image_array);
foreach($image_array as $files) {
//print_r($files);
$file_new_name = round(microtime(true)).$files['name'];
$destination = "public/img/".$file_new_name;
$file_name = $files['tmp_name'];
move_uploaded_file($file_name, $destination);
$data[] = __DIR__.('/../../../../../public/img/').$file_new_name;
}
return new JsonModel(array(
'data' => $data
));
}
基本上JSON
数据包含图片路径,但我希望在<div>
中显示图片。我怎样才能做到这一点?
答案 0 :(得分:0)
您可以使用JSON
格式,例如您可以使用的validate.php
;
echo json_encode(arrayvalue);
$("#btnsubmit").on('click', function(e) {
e.preventDefault();
var formData = $('#uploadform').serialize();
var files = $("#uploadform")[0];
console.log(files);
$.ajax({
url: '<?php echo $this->url('
upload ');?>',
type: 'POST',
data: new FormData(files),
dataType: 'json',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data) {
alert("Data Uploaded: " + data);
console.log(data);
$.each(data, function(i, item) {
alert(data[i].imgName);
});
},
error: function(result) {
alert("Error");
},
cache: false,
contentType: false,
processData: false
});
return false;
});