从 JavaScript 调用 php 函数 [英] Call php function from JavaScript

查看:30
本文介绍了从 JavaScript 调用 php 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法通过JS函数运行php函数?

Is there a way I can run a php function through a JS function?

像这样:

<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php 
query("hello");       ?>";    
}
</script>

<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;"     
onclick="test(); return false;"> test </a>
<span id="php_code"> </span>

我基本上想运行 php 函数 query("hello"),当我点击名为Test"的 href 将调用 php 函数时.

I basically want to run the php function query("hello"), when I click on the href called "Test" which would call the php function.

推荐答案

本质上,这就是 AJAX用于的.您的页面加载,并向元素添加一个事件.当用户触发事件时,例如通过单击某物,您的 Javascript 使用 XMLHttpRequest 对象 向服务器发送请求.

This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.

在服务器响应(大概是输出)之后,另一个 Javascript 函数/事件为您提供了一个处理该输出的地方,包括像任何其他 HTML 一样简单地将其粘贴到页面中.

After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.

您可以使用普通的 Javascript 来手工"完成,也可以使用 jQuery.根据您的项目大小和特定情况,使用纯 Javascript 可能更简单.

You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .

在这个非常基本的例子中,当用户点击一个链接时,我们向 myAjax.php 发送一个请求.服务器将生成一些内容,在本例中为hello world!".我们将放入 id 为 output 的 HTML 元素.

In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.

javascript

// handles the click event for link 1, sends the query
function getOutput() {
  getRequest(
      'myAjax.php', // URL for the PHP file
       drawOutput,  // handle successful request
       drawError    // handle error
  );
  return false;
}  
// handles drawing an error message
function drawError() {
    var container = document.getElementById('output');
    container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
    var container = document.getElementById('output');
    container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        // IE
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            // try an older version
            try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                return false;
            }
        }
    }
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req.readyState == 4) {
            return req.status === 200 ? 
                success(req.responseText) : error(req.status);
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}

HTML

<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>

PHP

// file myAjax.php
<?php
  echo 'hello world!';
?>

试试看:http://jsfiddle.net/GRMule/m8CTk/

可以说,这是很多 Javascript 代码.当然,您可以通过收紧块或使用更简洁的逻辑运算符来缩短它,但是那里还有很多事情要做.如果您计划在您的项目中做很多此类事情,那么使用 javascript 库可能会更好.

Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.

使用与上面相同的 HTML 和 PHP,这是您的整个脚本(页面中包含 jQuery).我已经稍微收紧了代码,以便与 jQuery 的一般风格更加一致,但你明白了:

Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:

// handles the click event, sends the query
function getOutput() {
   $.ajax({
      url:'myAjax.php',
      complete: function (response) {
          $('#output').html(response.responseText);
      },
      error: function () {
          $('#output').html('Bummer: there was an error!');
      }
  });
  return false;
}

试试看:http://jsfiddle.net/GRMule/WQXXT/

暂时不要急于使用 jQuery:添加任何库仍然会向您的项目添加数百或数千行代码,就像您编写它们一样确定.在 jQuery 库文件中,您会发现与第一个示例中的代码类似的代码,以及更多.这可能是一件好事,也可能不是.计划并考虑您项目的当前规模和未来扩展的可能性以及目标环境或平台.

Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.

如果这就是您需要做的全部,那么编写一次普通的 javascript 就大功告成了.

If this is all you need to do, write the plain javascript once and you're done.

文档

  • AJAX on MDN - https://developer.mozilla.org/en/ajax
  • XMLHttpRequest on MDN - https://developer.mozilla.org/en/XMLHttpRequest
  • XMLHttpRequest on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
  • jQuery - http://jquery.com/download/
  • jQuery.ajax - http://api.jquery.com/jQuery.ajax/

这篇关于从 JavaScript 调用 php 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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