2017-03-04 90 views
-2

我想执行下面的代码在PHP中;PHP:如何在javascript确认框后运行php代码?

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

基于该“OK”或“CANCEL”;

如果确定意味着我要执行下面的PHP代码,而无需使用AJAX

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"; 
} 
+1

简短的回答:没有Ajax,你不能这样做。长答案:你可以创建动态表单并提交,然后解析答案...不是一个好主意。 –

+0

'不使用AJAX' - 你不能... http不能这样工作 –

+1

为什么不使用AJAX? JavaScript运行在客户端上,php运行在服务器上,所以你将不得不回调服务器来运行它,这意味着AJAX或黑客。 –

回答

0

的一种方式,我觉得是,你可以传值的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,则执行其他任何你想做的事情。

$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?

0

您不能执行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>