按下按钮后调用JavaScript代码,然后刷新页面 [英] Call javascript code after press button and then refresh the page

查看:67
本文介绍了按下按钮后调用JavaScript代码,然后刷新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在按下按钮后启动一个php脚本,然后重新加载页面,但是我遇到了问题,现在我执行此操作:

 < a href =#class =btn green bigonclick =startUpdate();>开始更新< / a> 

然后这是脚本:

 < script type =text / javascript> 
函数startUpdate(){
$ .get(Update / startUpdateTxt.php);
返回false;
}
< / script>

这些脚本写在txt文件上,所有的作品都很完美,但我想刷新页面,因为我必须改变一些元素并阅读我在txt文件中做出的改变,所以我试图做到这一点:

 <脚本类型= 文本/ JavaScript的 > 
函数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')或死(无法打开文件);
$ stringData =StartUpdate\\\
;
fwrite($ fh,$ stringData);
fclose($ fh);
?>

我怎样才能刷新页面并在后台调用phpscript?

解决方案

您需要确保您的ajax调用完成。要做到这一点,您可以将您的重定向放在回调函数中:

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

然而,它并没有真正的意义(对我来说.. 。)使用ajax来调用一个php脚本然后重定向,只需发布​​到php脚本并处理所有内容就可以更容易。


i'm trying to start a php script after i press a button, and then reload the page, but i have a problem, now i do this:

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

then this is the script:

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

these script write on a txt file, all works perfect but i want refresh the page because i have to change some element and read the change i make in the txt file, so i have tried to do this:

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

        return window.location.href=window.location.href;
    }
</script>

in this way, the page is refreshed but the phpscript doesn't work anymore, and doesn't write anything in the file, this is the 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);
?>

how i can do to refresh the page and call in background the phpscript?

解决方案

You would need to make sure that your ajax call finishes. To do that, you could place your redirect in the callback function:

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

However, it does not really make a lot of sense (to me...) to use ajax to call a php script and then redirect, it would be easier to just post to the php script and handle everything from there.

这篇关于按下按钮后调用JavaScript代码,然后刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆