[英]Codeigniter ajax call error
我正在嘗試進行ajax調用以從數據庫中獲取結果,但是我遇到了錯誤。
我的JavaScript:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script language="Javascript">
setTimeout(makeAjaxCall, 1000);
function makeAjaxCall(){
$.ajax({
type: "post",
url: "call/update",
cache: false,
data: {action: 'getUpdate', term: '<?php echo $id;?>'},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
alert( obj['STATUS'] + obj['results']);
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
}
</script>
而我的控制器的方法:
public function update()
{
if (isset($_POST['action'])){
if ($_POST['action'] == 'getUpdate'){
pollNewData();
}
}
function pollNewData(){
$term = $_POST['term'];
$query = $this->db->query("SELECT * FROM users where guid <> '' and user_id = '$term'");
$res = $query->result();
echo json_encode(array('STATUS'=>200, 'results'=>$res));
}
}
我在chrome調試工具上遇到此錯誤:
500內部服務器錯誤)
你有幾個問題。 下面是工作代碼:
public function update()
{
if(!function_exists('pollNewData')){ // don't redeclare if already exists
function pollNewData($db){ // pass $db
$term = $_POST['term'];
$query = $db->query("SELECT * FROM users where guid <> '' and user_id = '$term'");
$res = $query->result();
echo json_encode(array('STATUS'=>200, 'results'=>$res));
}
}
if (isset($_POST['action'])){
if ($_POST['action'] == 'getUpdate'){
pollNewData($this->db); // pass $this->db
}
}
}
變化:
$this
上下文未在函數中設置,因此請將$db
對象作為參數傳遞。 function_exists()
檢查,因為在第二次調用時,它將嘗試重新聲明該函數並產生致命錯誤。 為了以后的調試,您應該打開錯誤:
error_reporting(E_ALL);
ini_set('display_errors', '1');
一些建議:
url: "<?php echo base_url();?>call/update",
//pollNewData();
echo $this->pollNewData(); //call like this and echo it out to the ajax
//echo json_encode(array('STATUS'=>200, 'results'=>$res));
return json_encode(array('STATUS'=>200, 'results'=>$res)); //return it instead to the calling function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.