如果条件在ajax中的成功回调函数中不起作用[关闭]

问题描述 投票:-1回答:1

这是我的main.js文件。我使用ajax发送和检索数据。我首先将所有数据发送到process.php文件。我处理文件,然后创建manage类的实例并调用该函数。一切正常,但问题是,如果条件不起作用,则在ajax成功函数中起作用。数据不等于给定的字符串。我检查了成功功能的响应。如果条件不起作用,它仍然与给定的相等字符串相同。

Main.js文件

$("body").delegate(".del_cat", "click",  function(){
    var del = $(this).attr("did");
    if(confirm("Are you sure ? You want to delete..!")) {
        $.ajax({
            url: DOMAIN+ "/include/process.php",
            method: "POST",
            data: {deleteCategory:1, id:del},
            success: function(data) {
                if(data == "DEPENDENT_CATEGORY") {
                    alert("Sorry You Can't delete it") 
                }else if(data == "CATEGORY_TABLE_DELETED") {
                    alert("Category deleted successfully")
                    managecategory(1);
                } else if(data == "TABLE_DELETED") {
                    alert("Deleted");
                } 
            }
        })
    } 

})

//这是process.php文件

(isset($_POST["deleteCategory"])) {
        $obj = new manage();
        $result = $obj->deleteRecords("categories", "cid", $_POST['id']);
        echo $result;
} 

//这是manage.php文件

public function deleteRecords($table, $pk, $id) {
        if($table == "categories") {
            $pre_stmt = $this->con->prepare("SELECT ".$id." FROM categories WHERE parent_cat= ?");
            $pre_stmt->bind_param("i", $id);
            $pre_stmt->execute();
            $result = $pre_stmt->get_result() or die($this->con->error);
            if($result->num_rows > 0) {
                return "DEPENDENT_CATEGORY";
            }   else {
                $pre_stmt = $this->con->prepare("DELETE FROM ".$table." WHERE ".$pk." = ?");
                $pre_stmt->bind_param("i", $id);
                $result = $pre_stmt->execute() or die($this->con->error);
                if($result) {
                    return "CATEGORY_TABLE_DELETED";
                }
            }
        } else {
            $pre_stmt = $this->con->prepare("DELETE FROM ".$table." WHERE ".$pk." = ? ");
            $pre_stmt->bind_param("i", $id);
            $result = $pre_stmt->execute() or die($this->con->error);
            if($result) {
                return "TABLE_DELETED";
            }
        }
    }
javascript php html ajax
1个回答
-3
投票

而不是使用if-else,而是使用switch(),并确保在default部分中输出数据以确保获得正确的反馈。

$.ajax(....
....
success: function(data) {
   switch(data) {
      case "DEPENDENT_CATEGORY"     : alert("Sorry You Can't delete it"); break;
      case "CATEGORY_TABLE_DELETED" : 
             alert("Category deleted successfully"); 
             managecategory(1);
             break;
      case "TABLE_DELETED": alert("deleted"); break;
      default: alert(`unrecognized response from server: [${data}]`);

   }
© www.soinside.com 2019 - 2024. All rights reserved.