javascript - 我可以从 javascript 或 jquery 调用在 php 中创建的函数吗?如何?

标签 javascript php jquery

我想通过 java 脚本或 jquery 在 php 中调用我的函数。

我试过了。

    <script>
    function hello(){
         <?php
              print_hello();
          ?>
    }

hello();

</script>

print_hello() 是我的 php 函数,它打印 hello。

最佳答案

无法直接调用 php 方法,它给出错误 not defined 因为在 javascript 文件中没有方法 print_hello

ReferenceError: print_hello is not defined

您必须使用 AJAX 从 javascript 调用 php 方法。

AJAX,有点棘手,如果你想让它变得简单,你可以使用 jQuery 库。

您必须将代码包含在文件的 print_hello 方法中,并使用 AJAX 调用该文件。假设您已将方法 print_hello 放入文件 print_hello.php 中,示例代码为:

$.ajax({
  url: "print_hello.php"
}).done(function() {
  alert( "called php code succesfully" );
});

然后把你的php代码放在文件php_hello.php

<?php
  print_hello();
?>

有关如何进行 ajax 调用的更多信息,请访问

Ajax jQuery

注意:(因为您是网络开发新手)

Web development is all about communication. In this case, communication between 2 parties, over the HTTP protocol:

The Server - This party is responsible for serving pages.

The Client - This party requests pages from the Server, and displays them to the user. On most cases, the client is a web browser. The User - The user uses the Client in order to surf the web, fill in forms, watch videos online, etc. Each side's programming, refers to code which runs at the specific machine, the server's or the client's.

More info At this StackOverflow Question (server side and client side programming)

关于javascript - 我可以从 javascript 或 jquery 调用在 php 中创建的函数吗?如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21872957/

相关文章:

jquery - 在 Bootstrap 模式中显示一张谷歌地图一页

php - 访问已解码的 json 字符串 PHP 中的字段

php - 函数仅定义但立即执行

javascript - 确定页面在 github 页面上已过时

Javascript如何找到滚动事件的来源

php - 代码逻辑不应允许查询通过,但它仍然允许 PHP SQL

jquery - 这些jquery选择器语句有什么区别

jquery - 触摸设备上的光滑轮播中同时出现 2 个点

JavaScript: "Dangling"引用 DOM 元素?

javascript - 悬停时 <li> 顶部的 DIV 菜单