2017-10-17 1009 views
0

我有一个有两个输入字段,文本和文件的窗体。我能够获得表单数据。但我正在努力做的是检索我发布数据的文件上的表单数据。如何检索通过xhr.send()发送的数据?

我的代码如下:

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

OK,经过一番研究,我设法解决这个问题。代码如下:

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(); 

}