单击按钮执行PHP文件,然后重定向

click button execute php file then redirect

本文关键字:然后 重定向 文件 PHP 按钮 执行 单击      更新时间:2023-09-26

祝大家美好的一天,

整天都在寻找如何做到这一点。我想要的是让每次"点击"进入一个 php 文件并确定将要执行的操作。

项操作.php

    include 'inc/database.php';
    include 'inc/functions.php';
    if ($_GET['action'] == 'delete') {
        // do delete action <-- this one is working
    } else if ($_GET['action'] == 'edit') {
        // do edit action; NOW HERE I WANT TO REDIRECT TO ANOTHER PAGE
        header("location: edit.php"); // I can't do something like this. Why?
    }

.html

<div class="action">    
    <a id="delete" href="itemAction.php" rel="<!--some_id-->"><img src="images/trash.ico" alt="delete"></a>
    <a id="edit" href="itemAction.php" rel="<!--some_id-->"><img src="images/Pencil-icon.png" alt="edit"></a>
</div>

.js

$("div.action a#delete").click(function (e) {
    var decision = confirm("Are you sure you want to delete the item?");
    if (decision) {
        e.preventDefault();
        $.get('itemAction.php', {action : 'delete', id : $(this).attr("rel")}, function (data) {            
            location.reload();
            alert("Succssfully deleted!");
        });
    }
    return false;
});
$("div.action a#edit").click(function (e) {
    e.preventDefault();
    $.get('itemAction.php', {action : 'edit', id : $(this).attr("rel")});
});

删除操作似乎正在工作。.但是我不能在编辑操作中做我想要的重定向到其他页面。有什么更好的方法可以做到这一点?任何帮助将不胜感激。谢谢

你不能这样做,因为ajax只会向你发送响应html,文本,xml或json响应,但不能做重定向。

对于重定向,您必须返回任何"redirectme.",并且根据该响应,您需要在javascript中添加代码以重定向到所需位置。

你能做的是?

在 PHP 文件中添加以下代码,

echo json_encode(array('status' => 'edit', 'url' => 'edit.php'));

根据上述响应,按如下方式修改您的$.get response callback

$.get('itemAction.php', {action : 'delete', id : $(this).attr("rel")},
   function (data)
   {
     if(response.status == 'edit'){
       window.location = response.url;
     }
});

它只是您需要根据需要设置的指南线。

评论回复

如果禁用了JS,则需要相应地进行编码。

首先,您需要修改HTML链接,如下所示,

<a id="delete" href="itemAction.php?action=delete&id=someid"
<a id="edit" href="itemAction.php?action=edit&id=someid"

并通过单击上面的链接使用其 href 属性传递到$.get如下所示。

$.get( $(this).href()

通过这样做,JS被禁用,您的代码也将起作用。

让你的按钮去某个地方

<form method="get" action="someScript.php">
    <button>Do things</button>
</form>

然后在someScript.php

<?php
// do things
header("Location: redirectToHere.php");