如何在ajax的URL中调用PHP函数?

时间:2014-12-17 06:03:45

标签: php html ajax

我编写了一个带有 echo 语句的单一函数的PHP代码,我希望在 ajax 代码中将该函数称为 url 。 我累了这么做。

<html>
    <head>
        <title>Writing PHP Function</title>

        <script>

        $.ajax(
        {
        url : localhost/practice.php/f=myFirst();
        type: "GET",
        data: dataString,

        success: function(result)
        {
        alert(result);
        }
        });

        </script>

    </head>
<body>

        <?php

            function myFirst()
            { 
             echo 'The First ran successfully.'; 
            }

        ?>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

你所拥有的东西有很多不妥之处。这只是一个适合您的简单示例。

<强> practice.php

<?php
    if(isset($_GET['f']))
        echo strip_tags($_GET['f']);
?>

<强>的index.php

<?php function myFirst() {
    echo 'The First ran successfully.';
} ?><html>
<head>
<title>Writing PHP Function</title>
<!-- You need to add the jQuery library -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
// You should activate it on an event like click (unless you want it to autoload)
$("#content").click(function() {
    $.ajax({
            // Your url is funky, and cannot be terminated with a semicolon
            // but rather a comma
            url : 'localhost/practice.php?f=<?php myFirst(); ?>',
            type: "GET",
            // You can do an alert, but I just made it populate a div instead
            success: function(result) {
                $("#place-to-load").html(result);
            }
        });
    });
</script>
    </head>
<body>
<!-- Your php function will not work as you intend because one -->
<!-- is a server-side function and the other is a client-side script -->
<!-- The functions are not interchangeable. That being said, you can -->
<!-- populate a javascript with a php variable but it would need to be -->
<!-- echoed like <?php myFirst(); ?> -->
<div id="place-to-load"></div>
<div id="content">Load</div>
</body>
</html>

答案 1 :(得分:0)

我会尝试根据URL中的params来调用这些函数。 Ajax部分,

$.ajax({url:'localhost/practice.php?f=myFirst',type:'GET'}).done(function(response){
  alert(response); // or you can write to your document
});

和PHP文件

<?php
      if(isset($_GET) && $_GET['f'] == 'myFirst'){
        myFirst();
      }else{
        die('No GET params received');
      }

      function myFirst(){ 
           echo 'The First ran successfully.'; 
      }

?>