2016-10-03 121 views
-1

我有一些問題試圖發佈數據CodeIgniter我有這個。AJAX POST到CodeIgniter控制器

阿賈克斯

$.ajax({ 
      url: $('#url').val() + "Dashboard/Index", 
      dataType: 'json', 
      contentType: 'application/json', 
      type: 'post', 
      data: {data: data}, 
      success: function(data){ 
       console.log(data); 
      }, 
      error: function(jqXhr, textStatus, errorThrown){ 
       console.log(jqXhr); 
       console.log(textStatus); 
       console.log(errorThrown); 
      } 
     }); 

控制器| Dashboard.php - >類:儀表板,功能:索引

atm我試着用這個只是爲了看看它的發佈,但沒有!

if($_POST) { 
      print_r($_POST); 
      die(); 
     } 

所以我的整個控制器看起來像這樣...

<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 

class Dashboard extends CI_Controller 
    public function index() 
    { 

     // $test = $_POST['data']; 
     // echo json_encode($_POST); 
     if($_POST) { 
      print_r($_POST); 
      die(); 
     } 


//////////////////////////////////Views///////////////////////////////// 



    // includes 
    $data['footer'] = $this->load->view('includes/footer', NULL, TRUE); 

    // App 
    $data['menuProfile'] = $this->load->view('app/menuProfile', NULL, TRUE); 
    $data['sidebarMenu'] = $this->load->view('app/sidebarMenu', NULL, TRUE); 
    $data['topNavigation'] = $this->load->view('app/topNavigation', NULL, TRUE); 
    $data['menuFooter'] = $this->load->view('app/menuFooter', NULL, TRUE); 

    // Dashboard 

    $dashboard['dinp'] = $this->load->view('app/dashboard/dinp', NULL, TRUE); 
    $dashboard['dispTitle'] = $this->load->view('app/dashboard/dispTitle', NULL, TRUE); 
    $dashboard['porcentaje'] = $this->load->view('app/dashboard/porcentaje', NULL, TRUE); 
    $dashboard['temp'] = $this->load->view('app/dashboard/temp', NULL, TRUE); 
    $dashboard['velocity'] = $this->load->view('app/dashboard/velocity', NULL, TRUE); 
    $data['dashboard'] = $this->load->view('app/dashboard/dashboard', $dashboard, TRUE); 


    $this->load->view('includes/head'); 
     $this->load->view('app', $data); 
    $this->load->view('includes/jquery'); 
    } 
} 

所以最終的輸出它只是這個:

Unexpected token < in JSON at position 0(…) 

我不知道爲什麼後返回整個HTML,我發佈我的數據作爲對象,我該怎麼辦?

+0

什麼是在阿賈克斯 – Rijin

+0

_ ** [對象,對象,對象,對象,對象,對象,對象,對象,對象,對象,對象使用「數據」的值/含量,對象,對象,對象] ** _它的數組(1)與10個對象 – Gil

+0

,因爲你使用數據類型json,你需要將數據轉換爲json – Rijin

回答

0

後數據包含JSON對象,你有你的對象是這樣的元素:)你

$this->input->post('your_post_element'); 
+0

好吧,這將工作,如果我的Ajax它的成功,但它得到一個錯誤因爲它獲取整個html,像這樣msg _ **「SyntaxError:位置0處的JSON中的意外標記H」(...)「** _ – Gil

+0

在ajax之前顯示您的JSON,使用JSON.stringify(data)並驗證您的objjct本網站:http://jsonlint.com/ –

0

1)你必須重新檢查,這是什麼變量

data: {data: data}, 

2內已設定

contentType: 'application/json' 

因此,您必須以JSON格式返回內容,並且應該將內容類型設置爲JSON的響應頁面

$this->output 
->set_content_type('application/json') 
->set_output(json_encode($_POST));