Ajax到卷曲表单提交

问题描述:

我有一个提交表单数据与文件到控制器的ajax,控制器将发送这个表单数据到我的api使用卷曲。我怎样才能做到这一点?Ajax到卷曲表单提交

我不能直接提交表单到我的API,它必须通过我的控制器。 :(

我的AJAX

data = new FormData(); 
     data.append('file', $('#file')[0].files[0]); 
     data.append('title', title); 
     data.append('description', description); 
     data.append('module_id', module_id); 
     data.append('tags', tags); 
     data.append('groups', groups); 
     $.ajax({ 
      url: '/controller/upload', 
      data: data, 
      processData: false, 
      contentType: false, 
      type: 'POST', 
      success: function (data) { 
       window.location.reload(); 
      } 
     }); 

我的控制器功能

public function uploadAction(){ 
    $response = new \Phalcon\Http\Response(); 
    $response->setContentType('application/json', 'UTF-8'); 
    $response2 = "{}"; 
    if($this->request->getPost()){ 
     $version = $this->session->get("version"); 
     $data = $this->request->getPost('data'); 
     $response2 = $this->useCurl("api_link","POST",$data); 
    } 
    return $response->setContent($response2); 
} 
+2

哪里是你的代码? – Hassaan

+0

'$ this-> useCurl'做什么? – Slytherin

url: '/controller/upload'应该是url: '/controller/uploadAction',,因为你调用内部controlleruploadAction方法

使用cURL:

function useCurl($api_link, $data){ 
      $ch = curl_init($api_link); 
      curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); 
      curl_setopt($ch, CURLOPT_POST, true); 
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 

      $ret = curl_exec($ch); 
      curl_close($ch); 
      return $ret; 
} 

在你的Ajax success回调:

success: function (data) { 
      //do something with data from uploadAction method (e.g console.log) 
      console.log(data); 
     }