在不离开当前页面的情况下从 Javascript 调用 PHP 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5306479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:44:04  来源:igfitidea点击:

Calling PHP scripts from Javascript without leaving current page

phpjavascripthtmljavascript-eventsonclick

提问by Riyan

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?

我在不离开当前 HTML 页面的情况下从 Javascript 调用 PHP 脚本时遇到了一些问题(如果可能的话)。我知道可以使用 AJAX,但是否可以单独使用 Javascript?

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.

我希望我的页面使用 Javascript(使用 onclick)执行一个简短的动画,然后立即调用一个 PHP 脚本将数据插入到 MySQL 数据库中——所有这些都不需要离开页面,所以它不会抑制动画。

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?

我可以做的动画部分以及将数据插入数据库等,但是如何在该 Javascript 动画函数的末尾调用 PHP 脚本?

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

任何指针、代码片段等将不胜感激!^_^

Apologies if this question has been asked previous.

如果之前有人问过这个问题,我们深表歉意。

回答by AbiusX

AJAX is Asynchronous Javascript And XML, Its a Javascript technology that allows you to send a request to the server (as your browser does when you enter a URL) and have the response in a javascript string instead of rendering it in the page.

AJAX 是异步 Javascript 和 XML,它是一种 Javascript 技术,允许您向服务器发送请求(就像您的浏览器在输入 URL 时所做的那样)并在 javascript 字符串中获得响应,而不是在页面中呈现它。

The problem is different browsers do not implement AJAX the same way, So I suggest using jQuery for abstraction.

问题是不同的浏览器不会以相同的方式实现 AJAX,所以我建议使用 jQuery 进行抽象。

do this with jQuery:

用 jQuery 做到这一点:

<script>
$.get("backend.php",{param:value},callbackFunction);
callbackFunction(data)
{
alert(data);
}

</script>

回答by Slinky Sloth

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.

碰巧遇到了同样的问题,所以我想出了类似的东西。您所要做的就是添加您需要的代码,并将 do_the_script 函数分配给 onclick 事件。

<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.

您可能已经注意到,“调用”地址的代码每 1 秒执行一次。这是为了确保调用足够多的次数以获得一个肯定的答案,然后调用 doneHandler 并清除间隔。如果您认为您的服务器可以更快或更慢地响应,您应该相应地更改这些毫秒。

回答by Naftali aka Neal

you can use jquery ajax:

你可以使用 jquery ajax:

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.ajax/

回答by Andrew Moore

PHP is a server-side language. JavaScript is a client-side language.

PHP 是一种服务器端语言。JavaScript 是一种客户端语言。

If you want to execute server-side code, you don't have the choice to do a round-trip to the server. If you don't want to leave the page, your only option is doing an asynchronous request (aka AJAX).

如果要执行服务器端代码,则无法选择往返服务器。如果您不想离开该页面,您唯一的选择就是执行异步请求(又名 AJAX)。

Using a JavaScript library such as jQueryor MooToolsgreatly simplifies that kind of task. For example, you could use MooToolsto do a request at the end of your script as such:

使用 JavaScript 库(例如jQueryMooTools)可以极大地简化此类任务。例如,您可以使用MooTools在脚本末尾执行请求,如下所示:

var req = new Request({url: '/backend/doPHPInsert.php'});
req.send();

There are ways to do so without AJAX by, for example, creating an iFrame dynamically (or any other element that fetches a resource).

有一些方法可以在没有 AJAX 的情况下实现,例如,动态创建 iFrame(或任何其他获取资源的元素)。

回答by alex

I understand it is possible using AJAX, although is it possible using Javascript alone?

我知道可以使用 AJAX,但是否可以单独使用 Javascript?

If you don't want to use XHR, you could use this ugly hack...

如果你不想使用 XHR,你可以使用这个丑陋的 hack ......

var request = 'mysql-insert.php',
    image = new Image();

image.onload = function() {
  // Success
}

image.onerror = function() {
  // Error
}

image.src = request;

Except that was only really used before widespread use of AJAX (or needing to make a cross domain request).

除了在广泛使用 AJAX 之前才真正使用(或需要进行跨域请求)。

I would just use AJAX. jQuery provides some great abstractions for working with XHR.

我只会使用 AJAX。jQuery 为使用 XHR 提供了一些很好的抽象。

回答by Ken Franqueiro

This has some good examples for using unadulterated XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

这有一些使用纯 XMLHttpRequest 的好例子:https: //developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

(Particularly, scroll down to the asynchronous examples - now you're cooking with gas.)

(特别是,向下滚动到异步示例 - 现在您正在使用燃气做饭。)

Edit: see also http://msdn.microsoft.com/en-us/library/ms535874%28v=vs.85%29.aspxwhich has examples for dealing with versions of IE which don't have native window.XMLHttpRequest.

编辑:另请参阅http://msdn.microsoft.com/en-us/library/ms535874%28v=vs.85%29.aspx,其中包含处理没有 native 的 IE 版本的示例window.XMLHttpRequest

Now, let's be frank - yes, working with XHR itself (especially cross-browser) is kind of obtuse. You can use just about anything out there(jQuery, Dojo, MooTools, Prototype, Closure, YUI, etc.) to do XHR more easily, because allof them, among other things, give you more concise XHR facilities.

现在,让我们坦率地说 - 是的,使用 XHR 本身(尤其是跨浏览器)有点迟钝。您可以使用任何现有的工具(jQuery、Dojo、MooTools、Prototype、Closure、YUI 等)来更轻松地执行 XHR,因为除其他外,所有这些为您提供了更简洁的 XHR 工具。

It's still good to know what you're working with under the surface before you start letting a library do it for you though. :)

不过,在您开始让图书馆为您完成工作之前,了解您在表面下使用的内容仍然很好。:)

回答by bodomalo

If you do not want to include the jquery library you can simple do the following

如果您不想包含 jquery 库,您可以简单地执行以下操作

a) ad an iframe, size 0px so it is not visible, href is blank

a) 广告 iframe,大小为 0px 所以它不可见,href 为空

b) execute this within your js code function

b) 在你的 js 代码函数中执行这个

 window.frames['iframename'].location.replace('http://....your . php');

This will execute the php script and you can for example make a database update...

这将执行 php 脚本,您可以例如进行数据库更新...