按下按钮后调用javascript代码,然后刷新页面


Call javascript code after press button and then refresh the page

我试图启动一个PHP脚本后,我按下一个按钮,然后重新加载页面,但我有一个问题,现在我这样做:

<a href="#" class="btn green big" onclick="startUpdate();">Start Update</a>

则脚本如下:

<script type="text/javascript">
    function startUpdate() {
        $.get("Update/startUpdateTxt.php");
        return false;
    }
</script>

这些脚本写在一个TXT文件上,所有的工作都很完美,但我想刷新页面,因为我必须改变一些元素,并阅读我在TXT文件中所做的改变,所以我试着这样做:

 <script type="text/javascript">
    function startUpdate() {
        $.get("Update/startUpdateTxt.php");
        return window.location.href=window.location.href;
    }
</script>

这样,页面被刷新了,但是phpscript不再工作了,并且没有在文件中写入任何内容,这是phpscript:

startUpdateTxt.php:

<?php
$myFile = "updateStatus.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "StartUpdate'n";
fwrite($fh, $stringData);
fclose($fh);
?>

我该如何刷新页面并在后台调用php脚本?

您需要确保ajax调用完成。为此,可以将重定向放在回调函数中:

function startUpdate() {
    $.get("Update/startUpdateTxt.php", function() {
      location.reload();
    });
}

然而,它并不是真的有很多意义(对我来说…)使用ajax调用php脚本,然后重定向,它会更容易只是张贴到php脚本和处理一切从那里。