使用ajax请求调用.php文件 - wordpress

问题描述 投票:0回答:2

我试图从wordpress中的ajax请求调用一个php文件。我遇到的问题是ajax请求需要一个php文件的路径。我不确定在我的wordpress安装中将这个php文件放在哪里。此外,此文件不能包含在内,因为我只有在用户决定调用它时才需要调用此php文件。我现在不使用jquery,但是可以使用它,因为我很确定只有客户端,所以服务器不必参与。

作为我想要做的事情的一个例子,让我们用一个表格来尝试。这个例子来自http://thisinterestsme.com/ajax-form-submission-php/

我会在网页中包含这个。

<html>
    <head>
        <meta charset="UTF-8">
        <title>Example Ajax PHP Form</title>
    </head>
    <body>

        <form id="my_form_id">
            Your Email Address: <input type="text" id="email" /><br>
            <input type="submit" />
        </form>

        <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
        <script>
            $(document).ready(function(){
                $('#my_form_id').on('submit', function(e){
                    //Stop the form from submitting itself to the server.
                    e.preventDefault();
                    var email = $('#email').val();
                    $.ajax({
                        type: "POST",
                        url: 'submission.php',
                        data: {email: email},
                        success: function(data){
                            alert(data);
                        }
                    });
                });
            });
        </script>
    </body>
</html>

然后在服务器上的其他地方我会有这个文件。问题是我不知道放置此文件的位置或上面给出ajax请求的路径。

<?php
$emailAddress = false;
if(isset($_POST['email'])){
    $emailAddress = $_POST['email'];
}

echo 'Received email was: ' . $emailAddress;
?>
javascript php jquery ajax wordpress
2个回答
1
投票

假设你有这个php:

<?php
 $emailAddress = false;
 if(isset($_POST['email'])){
    $emailAddress = $_POST['email'];
 }

 echo 'Received email was: ' . $emailAddress;
?>

您应该将此文件命名为page-submission.php并将其保存在functions.php所在的位置,然后创建一个空白页面名称“submission”。您现在可以在ajax中调用此文件作为/ submission。

以下是视觉层次结构的工作原理:

enter image description here


1
投票

您可以将PHP函数添加到functions.php文件中,该文件可以从ajax轻松执行:

function post_email_address(WP_REST_Request $request){
  return 'Received email was: ' . $request['email'];
}

add_action('rest_api_init', function(){
  register_rest_route( 'foo/v1', '/postEmail', array(
    'methods' => 'POST',
    'callback' => 'post_email_address',
  ));
});

然后在你的前端:

  $(function(){
    $('#my_form_id').submit(function(e){
      //Stop the form from submitting itself to the server.
      e.preventDefault();
      var email = $('#email').val();
      $.post("/wp-json/foo/v1/postEmail", {
        email: email
      },function(data){
        console.log(data);
      });
    });
  });

“foo”是命名空间,您可以使用与您的应用程序更相关的内容。

© www.soinside.com 2019 - 2024. All rights reserved.