PHP:如何在javascript确认框后运行php代码?

时间:2017-03-04 11:01:16

标签: javascript php html ajax

我想在php中执行以下代码;

//declare movies as a class field
List<Movies> movies;
...
private List<Movies> getDataFromServer(int page)
{
...
call.enqueue(new Callback<Response>() {
    @Override
    public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
        dataIsReady(response.body().getMovies();
    }

    @Override
    public void onFailure(Call<Response> call, Throwable t) {
        Log.e(TAG,t.toString());
        movies = null;
    }
});
}

private void dataIsReady(List<Movies> movies){
    this.movies = movies;
  //do what you want with movies
}

基于那个&#34; OK&#34;或&#34;取消&#34; ;

如果那个确定意味着我想在不使用AJAX的情况下执行PHP代码

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

2 个答案:

答案 0 :(得分: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,则执行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?

答案 1 :(得分:0)

你不能在javascript中执行MySQL或PHP命令,你可以做的是创建一个可以通过Ajax调用的PHP函数。最好的方法是使用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>