Calling PHP scripts from Javascript without leavin

2019-02-23 07:00发布

I'm having some trouble calling PHP scripts from Javascript without leaving the current HTML page (if it is at all possible). I understand it is possible using AJAX, although is it possible using Javascript alone?

Context:-

I want my page to perform a short animation using Javascript (using onclick), then immediately call a PHP script to insert data into a MySQL database - all without leaving the page so it does not inhibit the animation.

The animation part I can do and the inserting the data into the database, etc. but how can I call a PHP script at the end of that Javascript animation function?

Any pointers, code fragments, etc. would be greatly appreciated! ^_^

Apologies if this question has been asked previous.

7条回答
Summer. ? 凉城
2楼-- · 2019-02-23 07:58

Just happened to have the same issue, so I came up with something like that. All you have to do is add the code you need, and assign the do_the_script function to the onclick event.

<script type="text/javascript">
var myIntv;
function do_the_script() {
    // play animation ...
    var address='fancy_script.php';
    var tmp = new XMLHttpRequest();
    myIntv=setInterval(function(){
    tmp.addEventListener("load", doneHandler, false);
    tmp.open("POST", address);
    tmp.send(null);
    }, 1000);
}

function doneHandler(event) {
    // maybe do something when script is executed
    clearInterval(myIntv);
}
</script>

As you may have noticed, the code that "calls" the address is executed every 1 second. This, is to ensure that the call is made enough times so as to get a single positive answer, call the doneHandler and clear the interval afterwards. If you believe that your server can respond faster or slower you should change those milliseconds accordingly.

查看更多
登录 后发表回答