【问题标题】:PHP : How to run php code after javascript confirm box?PHP:如何在 javascript 确认框后运行 php 代码?
【发布时间】:2017-03-04 19:23:22
【问题描述】:

我想在php中执行下面的代码;

var answer =window.confirm("Did You want to overwrite the file..."); 

基于那个“OK”或“CANCEL”;

如果没问题意味着我想在不使用 AJAX 的情况下执行以下 php 代码

if($uploadedby==$name)
{
    move_uploaded_file($file_loc,$folder.$file);
    $sql="update  pubfiles SET filename='$file',owner_name='$name',upload_time='$file_time',size='$file_size' WHERE content='$unique';";

    $qry=mysql_query($sql,$conn); 
    if($qry>0)$check="yes";
}

【问题讨论】:

  • 简短回答:没有 ajax,你不能这样做。长答案:您可以创建动态表单并提交它,然后解析答案......这不是一个好主意。
  • without using AJAX - 你不能……http不能那样工作
  • 为什么没有 AJAX? javascript 在客户端运行而 php 在服务器上运行,因此您将不得不回调服务器来运行它,这意味着 AJAX 或 hack。
  • 你可以使用 websockets,但这会比 Ajax 困难得多,而且 php 也不是最好的选择。

标签: javascript php html ajax


【解决方案1】:

我发现的一种方法是您可以将一个值传递给 url,然后在 php 中获取它。

function getParameterByName(name, url) {
        if (!url) {
          url = window.location.href;
        }
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }

    var id = getParameterByName('id');

    if(!id)
    {
        var id =window.confirm("Did You want to overwrite the file...");        
        window.location.href = "test.php?id="+id
    }

在我们的例子中是 id,如果 id 设置为 true,则执行 else 任何你想做的事情。

$id = $_GET['id'];

if($uploadedby==$name && $id == true)
{
    move_uploaded_file($file_loc,$folder.$file);
    $sql="update  pubfiles SET filename='$file',owner_name='$name',upload_time='$file_time',size='$file_size' WHERE content='$unique';";

    $qry=mysql_query($sql,$conn); 
    if($qry>0)$check="yes";
}

在javascript中解析url的功劳:

How can I get query string values in JavaScript?

【讨论】:

    【解决方案2】:

    你不能在 javascript 中执行 MySQL 或 PHP 命令,你可以做一个 PHP 函数,你可以通过 Ajax 调用。最好的方法是使用 jQuery 或在 URL 中使用 PHP 函数重定向页面。

    请戳:How to execute the code inside javascript confirm box

    <script type="text/javascript">  
        if (confirm("This seems to be Duplicate. Do you want to continue ?"))
        {
            $.ajax({
                url: 'your_path_to_php_function.php',
                type: 'POST', // Or any HTTP method you like
                data: {data: 'any_external_data'}
            })
            .done(function( data ) {
                // do_something()
            });
        }
        else
        {
            window.location = 'your_url?yourspecialtag=true'
        }
     </script>
    

    【讨论】:

      猜你喜欢
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      相关资源
      最近更新 更多