0

我正在尝试使用 ajax 和 php 轮询我正在编写的应用程序。php 本质上接收一个字符串化对象以放入文件中,以后可以读取该文件。我写的对象工作得很好。我现在遇到的问题是,如果 php 尝试读取一个不存在的文件,它似乎会向 $.post() 调用返回错误代码。我希望它返回 JSON,并且成功,以便我可以处理有点不同。

有问题的php如下:

public function read(){
        $id = $this->input->post('id');
        $test = fopen("./meetings/".$id.".mt", 'r');
        if(!$test){
            error_log("Unable to open file, you mutt!");
            echo json_encode(array('status' => "FAIL"));
        }else{
        error_log("Here! 2");
        $obj = array();
            while(!feof($test)){
                error_log("Here! 3");
                $tmp = fgets($test);
                error_log("Here! 4");
                if($tmp){
                    $obj[count($obj)] = $tmp;
                }
            }
            fclose($test);
            error_log("Here! 5");
        if(!count($obj) > 0){
            echo json_encode(array('status' => "FAIL"));
        }
        echo json_encode(array('status' => 'OKAY', 'obj' => $obj));
        }
    }

和Javascript(使用jquery)如下:

function read(){
        $.post('<?php echo base_url(); ?>meetings/read', {id: <?php echo $id;?>}, function(json){
            console.log(json.status);
            if(json.status == 'OKAY'){
                for(var i = 0 ; i < json.obj.length ; i++){
                    parseObject(json.obj[i]);
                }
            }
        }, 'json');
    }

javascript 没有成功功能,我检查使用ajaxError()但我不知道如何解决这个问题,甚至不知道为什么 php 发送错误,因为我认为我正在检查它。否则,php 将按预期工作。此外,轮询确实尽可能频繁地调用服务器。有关解决此问题的任何建议吗?如果您需要更多信息,请询问。谢谢!

4

1 回答 1

2
public function read(){
   $id = $this->input->post('id');

   /* changes */
   $path = "./meetings/".$id.".mt";
   if (!file_exists($path)){
     echo json_encode(array('status' => "FAIL")); 
     return;// this exit from here and go to js file
   }
   /* changes ends */

    $test = fopen($path, 'r');
    if(!$test){
        error_log("Unable to open file, you mutt!");
        echo json_encode(array('status' => "FAIL"));
    }else{
    error_log("Here! 2");
    $obj = array();
        while(!feof($test)){
            error_log("Here! 3");
            $tmp = fgets($test);
            error_log("Here! 4");
            if($tmp){
                $obj[count($obj)] = $tmp;
            }
        }
        fclose($test);
        error_log("Here! 5");
    if(!count($obj) > 0){
        echo json_encode(array('status' => "FAIL"));
    }
    echo json_encode(array('status' => 'OKAY', 'obj' => $obj));
    }
}

我使用固定常量尝试了您的代码并且它有效。如果仍然面临错误,请在 try-catch 块中包装“fopen”。在其他情况下,请检查路径设置。使用萤火虫查看实际生成的 JS。如果卡住,请使用它。

于 2013-05-01T20:36:05.063 回答