[英]Call Php controller function with AJAX Codeigniter
我與Ajax和Codeigniter一起使用來調用函數client-server
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不顯示任何數據,我做錯了什么?
好吧,ajax調用從服務器讀取響應,並且該響應必須呈現為某種類型的可讀數據,例如application/json
或text/html
。
為了寫入該數據,您需要使用PHP從服務器上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"));
}
將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屬性內添加dataType
屬性,如下所示:
$.ajax({
...
dataType : 'json', // with this, no need to write JSON.parse()
...
});
我還很新,因為我只使用過AJAX,但是我認為您的代碼有一些語法錯誤。
我建議您需要查看更多有關ajax調用的示例來修復這些小錯誤。
您說您的JS正在運行,但沒有顯示數據?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.