我有一个包含两个输入字段,文本和文件的表单。我能够获取表单数据。但我正在努力做的是检索我发布数据的文件上的表单数据。
我的代码如下:
function addAnswer() {
// var currentUser = 2;
var formData = new FormData();
//Get comments
var comments = document.getElementById("res_comm").value;
if (comments.length < 1) {
alert("Please input some commetns");
}
//Get picture from form
var logo = document.getElementById('res_files');
//Check if theres a comment
if (logo.files.length > 0) {
formData.append("res_files", logo.files[0]);
exit();
}
formData.append("comments", comments);
formData.append("update_id", UpdateID);
console.log(...formData);
var xhr = new XMLHttpRequest();
xhr.open('POST', './nonconfirmitys/savedata.json', true);
xhr.send(formData);
//location.reload();
}
答案 0 :(得分:0)
在致电发送之前,请捕获xhr
之一的事件。 onreadystatechange
与浏览器兼容,但涉及的代码更多。 onload
可能是一个很好的候选人。加载后,xhr
有许多属性可以查看从服务器返回的内容。
请参阅:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
答案 1 :(得分:0)
好的,经过一番研究,我设法解决了这个问题。代码如下:
public function savedata()
{
$this->autoRender = false;
$this->response->type('json');
$json = json_encode(array('message'=>'Input some stuff here!'));
$this->response->body($json);
//var_dump($this->request->data);
$comments = $_POST['comments'];
$id = $_POST['update_id'];
$currentUser = $this->Auth->user();
$this->request->data['usr_id'] = $currentUser['User']['usr_id'];
if (!empty($_FILES)) {
$file = $_FILES['res_files'];
$rawFilename = explode('.', $file['name']);
$originalextention = $rawFilename[count($rawFilename)-1];
$filename = md5('picture'.time()).'.'.$originalextention;
$newName = $filename;
}
else{
$filename= "";
}
if (empty($newName)) {
$this->set('errors', $this->jsonResponse('FAL', 'File not uploaded, Please try again'));
return $this->set('_serialize', 'errors');
}
if (!empty($_FILES)) {
$file = $_FILES['res_files'];
$uploadDir = WWW_ROOT . DS . 'files' . DS;
move_uploaded_file($file['tmp_name'], $uploadDir.$filename);
}
$this->loadModel('Nonconfirmity');
$this->Nonconfirmity->read(null, $id);
$this->Nonconfirmity->set('res_comments', $comments);
$this->Nonconfirmity->set('res_user_id', $this->request->data['usr_id']);
$this->Nonconfirmity->set('res_files', $filename);
$this->Nonconfirmity->set('res_date', date('Y-m-d H:i:s'));
$this->Nonconfirmity->set('res_status', "Solved");
$this->Nonconfirmity->save();
$this->Nonconfirmity->save();
}