如何在 JavaScript 中调用 PHP 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5984545/
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
How to call a PHP function in JavaScript?
提问by Newbie Coder
I have
我有
index.php
index.php
<select id="year_list" name="year_list" onchange="check_year_event('year_list', 'event_list');" > . . . </select>
<select id="event_list" name="event_list" onchange="check_year_event('year_list', 'event_list');" > . . . </select>
.
.
.
<?php
function checkYearandEvent($year, $event) {
$year_event = mysql_query("SELECT * FROM year_event WHERE year = '$event' AND event = '$event'")
if (mysql_num_rows($year_event) > 0) {
// do this
}
}
?>
myscripts.js
myscripts.js
function check_year_event(year_id, event_id) {
var year = document.getElementById(year_id).value;
var event = document.getElementById(event_id).value;
// call PHP function (but I don't know how): checkYearandEvent(year, event);
}
My question is how do I call the PHP function every time the user changes the value of any of the select
element.
我的问题是每次用户更改任何select
元素的值时如何调用 PHP 函数。
采纳答案by Galled
You need to use ajax. There is a basic example:
你需要使用ajax。有一个基本的例子:
myscripts.js
我的脚本.js
function AjaxCaller(){
var xmlhttp=false;
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(E){
xmlhttp = false;
}
}
if(!xmlhttp && typeof XMLHttpRequest!='undefined'){
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function callPage(url, div){
ajax=AjaxCaller();
ajax.open("GET", url, true);
ajax.onreadystatechange=function(){
if(ajax.readyState==4){
if(ajax.status==200){
div.innerHTML = ajax.responseText;
}
}
}
ajax.send(null);
}
function check_year_event(year_id, event_id) {
var year = document.getElementById(year_id).value;
var event = document.getElementById(event_id).value;
callPage('file.php?year='+year+'&'+'event=+'+event,document.getElementById(targetId));
}
file.php
文件.php
<?php
function checkYearandEvent($year, $event) {
$year_event = mysql_query("SELECT * FROM year_event WHERE year = '$event' AND event = '$event'")
if (mysql_num_rows($year_event) > 0) {
// do this
}
}
echo checkYearandEvent($_GET['year'], $_GET['event']);
?>
回答by jimbo
You won't be able to do this in the way you might be expeting to. PHP is executed on the server, before the browser receives the HTML. On the other hand, JavaScript runs in the browser and has no knowledge of the PHP (or any other server side language) used to create the HTML.
您将无法以您可能期望的方式做到这一点。PHP 在浏览器接收 HTML 之前在服务器上执行。另一方面,JavaScript 在浏览器中运行并且不了解用于创建 HTML 的 PHP(或任何其他服务器端语言)。
To "call" a php function, you have to issue a request back to the server (often referred to as AJAX). For example, you could have a checkYear.php
script which checks the event and returns some HTML indicating whether the check succeeded. When the HTML fragment gets back to the JavaScript, you inject it into the page.
要“调用”一个 php 函数,您必须向服务器发出一个请求(通常称为 AJAX)。例如,您可以有一个checkYear.php
脚本来检查事件并返回一些指示检查是否成功的 HTML。当 HTML 片段返回到 JavaScript 时,您将其注入到页面中。
Hope this helps!
希望这可以帮助!
回答by RichW
JavaScript is a client side language, PHP is a server side language. Therefore you can't call PHP functions directly from JavaScript code. However, what you can do is post an AJAX request (it calls a PHP file behind the scenes) and use that to run your PHP code and return any data you require back to the JavaScript.
JavaScript 是客户端语言,PHP 是服务器端语言。因此,您不能直接从 JavaScript 代码调用 PHP 函数。但是,您可以做的是发布一个 AJAX 请求(它在幕后调用一个 PHP 文件)并使用它来运行您的 PHP 代码并将您需要的任何数据返回给 JavaScript。
回答by Tadeck
Basically, you are mixing server-side (PHP) and client-side (JS) scripting.
基本上,您正在混合服务器端 (PHP) 和客户端 (JS) 脚本。
It is however possible - thanks eg. to AJAX. Because you was not specific about what do you exactly need to be done after the select box changes, I can only point you to some resources and propose following:
然而,这是可能的 - 谢谢,例如。到 AJAX。因为您没有具体说明选择框更改后您到底需要做什么,所以我只能向您指出一些资源并提出以下建议:
- learn and start using jQuery (jquery.com) - it will help you get started and maintain cross-browser compatibility,
- learn how to make AJAX requests (eg. in the function you just were firing when
onchange
event was fired) - eg. using .post()jQuery function, - learn how to return data from PHP (eg. using
json_encode()
in PHP, but raw HTML is also ok) and use it in JS,
- 学习并开始使用 jQuery ( jquery.com) - 它将帮助您入门并保持跨浏览器兼容性,
- 学习如何发出 AJAX 请求(例如,在触发
onchange
事件时刚刚触发的函数中) - 例如。使用.post()jQuery 函数, - 学习如何从 PHP 返回数据(例如
json_encode()
在 PHP 中使用,但原始 HTML 也可以)并在 JS 中使用它,
回答by Nicolás Ozimica
There may be many ways to do this. The one I prefer, is using MooTools
Request
object.
可能有很多方法可以做到这一点。我更喜欢的是使用MooTools
Request
对象。
For example, you have a script called ajaxCallable.php
, which receives thru $_REQUEST
variables some parameters, then you do (in the Javascript side):
例如,您有一个名为 的脚本ajaxCallable.php
,它通过$_REQUEST
变量接收一些参数,然后您(在 Javascript 端)执行以下操作:
function check_year_event(year_id, event_id) {
var year = document.getElementById(year_id).value;
var event = document.getElementById(event_id).value;
var myRequest = new Request({method: 'get', url: 'ajaxCallable.php'});
myRequest.send('yearVar=' + year + '&eventVar=' + event);
}
then, your ajaxCallable.php
will be able to access the variables: $_REQUEST['yearVar']
and $_REQUEST['eventVar']
.
然后,您ajaxCallable.php
将能够访问变量:$_REQUEST['yearVar']
和$_REQUEST['eventVar']
。
回答by e.w. parris
I was working on a project this week and came up with an easy way to call a php script from an onclick(). It goes like this.
这周我正在做一个项目,并想出了一种从 onclick() 调用 php 脚本的简单方法。它是这样的。
I define an onclick() call in this case on a div called "sidebarItem"…
在这种情况下,我在名为“sidebarItem”的 div 上定义了一个 onclick() 调用……
<a><div class="sidebarItem" onclick="populate('#content', 'help', 'open')">Click me for new content</div></a>
Then I made a simple little JS function that loads an external file into the target container…
然后我做了一个简单的小 JS 函数,将外部文件加载到目标容器中……
function populate($container, $page, $item){
$($container).load('cyclorama/includes/populate.php?$page='+$page+'&$item='+$item);}
Then I write a small php file that gets the $page and $item, queries the database and returns the new content.
然后我写了一个小的php文件,获取$page和$item,查询数据库并返回新的内容。
<?php
$page = $_GET['$page'];
$item = $_GET['$item'];
$getContentQuery = "SELECT content FROM myTable WHERE page='".$page."' AND item='".$item."'";
$content = mysql_query($getContentQuery, $db);
$myContent = mysql_fetch_assoc($content);
echo $myContent['content'];?>
The php script echoes the new content and it's loaded into the container. I think there are a lot of places this could serve. I'd be interested in finding out if there are any obvious reasons NOT to do this. It doesn't use AJAX just javascript and php but it's fast and relatively easy.
php 脚本回显新内容并将其加载到容器中。我认为这可以用于很多地方。我很想知道是否有任何明显的理由不这样做。它不只使用 javascript 和 php 的 AJAX,但它快速且相对容易。