2017-02-17 44 views
0

我,即時訪問的php控制器功能使用Ajax和笨工作呼叫功能的客戶端 - 服務器與AJAX笨

php的

public function mainViewClean() { 


     unset($_SESSION[$this::jsondevices]); 
     unset($_SESSION[$this::jsontags]); 
     return "Ready"; 
    } 
//route $route['cleantags']  = 'user/mainViewClean'; 

和Ajax:

<script type="text/javascript"> 
    $(document).ready(function(){ 
     $("#btn_recargar").button().click(function(){ 

      //window.location.href = "<?= base_url('home')?>"; 
      $.ajax({ 
       type:'POST', 
       url:'<?php echo base_url("cleantags"); ?>', 
       data:{'id':100}, 
       success:function(data){ 
       //window.location.href = "<?= base_url('home')?>"; 
        alert(data); 
       } 
      }); 

    }); 
}); 
</script> 

功能的藉口好,但JavaScript不顯示任何數據,什麼即時通訊做錯了?

回答

1

更改return到:

echo "Ready"; 

如果您發送的陣列,在服務器端,您需要json_encode,例如:

// encode array into json string format 
echo json_encode(array('name' => 'Osman')); 

而且在JS,你有2種選擇,第一種解決方案是:

success : function (data) { 
    // data now is coming in this form { "name" : "osman" } 
    // as the string data is coming from server-side 
    // you must parse it back into Javascript object 
    var newData = JSON.parse(data); 
} 

而第二個選項是,加AJAX屬性內種性能如以下:

$.ajax({ 
    ... 
    dataType : 'json', // with this, no need to write JSON.parse() 
    ... 
}); 
+0

謝謝,如果我需要發送對象,首先我需要編碼正確嗎? –

+0

是的,查看更新回答 –

+0

感謝您的回覆 –

2

那麼,AJAX調用讀取來自服務器的響應,並且響應必須被呈現爲某種類型的可讀數據的,諸如application/jsontext/html

爲了編寫這些數據,您需要從服務器上使用echo

return語句不寫入數據,它只是在服務器級別返回。

如果要在PHP函數之間進行通信,則必須使用return。但是,如果你要輸出一些數據,你必須使用echo

客戶端

$.ajax({ 
      url:'<?php echo base_url("cleantags"); ?>', 
      dataType: 'application/json', 
      success:function(response) 
      { 
        alert(response.foo); 
      } 
     }) 

服務器端

public function mainViewClean() 
    { 
     unset($_SESSION[$this::jsondevices]); 
     unset($_SESSION[$this::jsontags]); 
     echo json_encode(array("foo"=>"Ready")); 
    } 
0

我是相當新的,我只是一直使用AJAX,但我認爲你的代碼有一些語法錯誤。

  • 數據:{id:100}周圍沒有引號。

我建議你需要看看更多的Ajax調用的例子來解決這些小錯誤。

你說你的JS工作但沒有顯示數據?

+1

'id'不需要引號,'data:{id:100}'就足夠了,'.button()'函數是'jquery UI'。 –

+0

確實它將元素更改爲可點擊的按鈕。搜索並在文檔中找到它 – nivanmorgan