简体   繁体   English

使用AJAX调用在PHP文件之间发送POST参数

[英]Sending POST parameters between PHP files using AJAX calls

I have a PHP file test.php that has a simple link, which after being clicked, calls an AJAX function to send data as POST parameters to another file testPHP.php. 我有一个PHP文件test.php,它具有一个简单的链接,单击该链接后,将调用AJAX函数以将POST参数作为数据发送到另一个文件testPHP.php。 The second file then receives the POST parameters from the AJAX call and then alerts the contents inside the $_POST array. 然后,第二个文件从AJAX调用接收POST参数,然后警告$ _POST数组中的内容。 The issue I am facing is that in the second file, the $_POST array is empty (I checked that using print_r($_POST)), so I think that the data hasn't passed through. 我面临的问题是,在第二个文件中,$ _ POST数组为空(我使用print_r($ _ POST)进行了检查),因此我认为数据尚未通过。 These are the 2 files: 这些是2个文件:

test.php test.php的

  <a id="link" role="button" href="testPHP.php">Test</a>

  <script type="text/javascript">

  $("#link").click(function(e) {
    e.preventDefault();
    alert('function entered');
    $.ajax({
     url: "testPHP.php",
      type: "POST",
      data: {
        parameter1: 'test', 
        parameter2: 'test2'},
      success: function(msg) {
        alert('wow' + msg);
      }

    });
    alert('function end');
    document.getElementById('#link').setAttribute('href','testPHP.php');
  });

testPHP.php testPHP.php

if(isset($_GET))
{
  echo "<script>alert('GET is there');</script>";
  print_r($_GET);
}
if(isset($_POST))
{
  echo "<script>alert('POST is there')</script>";
  print_r($_POST);
}
if(isset($_POST['parameter1']))
{
  echo "<script>alert('$_POST is set')</script>";
  header('Location: HomePage.php');
}
else
{
  echo "<script>alert('No post variable set')</script>";
}

What I have tried so far is to send a SUCCESS message if the AJAX call has been executed successfully, and it does alert me the Success message. 到目前为止,我所尝试的是如果AJAX调用已成功执行,则发送SUCCESS消息,并且确实会提醒我成功消息。 I have also checked to see the contents of the $_POST array in the 2nd file to see if I am receiving data in a format other than a POST request (like a string that might have to be exploded to get the contents), but the $_POST array comes up empty. 我还检查了第二个文件中的$ _POST数组的内容,以查看我是否以除POST请求之外的其他格式(例如,可能需要分解以获取内容的字符串)接收数据,但是$ _POST数组为空。 This is the output I get when it redirects to the 2nd page: Array() Array() The $_POST and $_GET (for testing purpose) arrays come up empty. 这是重定向到第二页时得到的输出:Array()Array()$ _POST和$ _GET(用于测试目的)数组为空。

I have also gone through the AJAX documentation, but can't get this simple POST data transfer to work. 我也阅读了AJAX文档,但是无法使这种简单的POST数据传输正常工作。 Can someone please help me with this issue so that I can understand how to properly send POST parameters and receive the data into $_POST['parameter1'] and $_POST['parameter2'] strings so I can process the data further. 有人可以帮我解决这个问题,以便我了解如何正确发送POST参数并将数据接收到$ _POST ['parameter1']和$ _POST ['parameter2']字符串中,以便我进一步处理数据。

Note : I have used the FORM's POST method using hidden form elements and that works fine, but I want to try this approach to better understand how AJAX works. 注意 :我已经使用了使用隐藏表单元素的FORM的POST方法,并且效果很好,但是我想尝试这种方法以更好地了解AJAX的工作原理。

A slightly different version of the above which should help you solve your problem. 上面的版本略有不同,应该可以帮助您解决问题。 For ease in debugging it is all one page but you can clearly see the script in operation once you click the button. 为了便于调试,它全都是一页,但是单击按钮后,您可以清楚地看到正在运行的脚本。 Simply echo ing javascript in the php code and hoping it will execute client side is not going to work - simply echo a message or a JSON object would be better. 只是在php代码中echo javascript并希望它将在客户端执行将不起作用-只需回显一条消息或JSON对象会更好。

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();

        print_r( $_POST );

        exit();
    }

?>
<!doctype html>
<html>
    <head>
        <title>jQuery - ajax experiments</title>
        <script src='//code.jquery.com/jquery-latest.js'></script>

    </head>
    <body>
        <a id='link' role='button' href='#'>Test</a>
        <script>
            $('#link').click(function(e) {
                e.preventDefault();
                alert('function entered');
                $.ajax({
                    url: location.href,
                    type: 'POST',
                    data: {
                        parameter1: 'test', 
                        parameter2: 'test2'
                    },
                    success: function(msg) {
                        alert( 'wow' + msg );
                    }

                });
                alert('function end');
            });
        </script>
    </body>
</html>

As 2 separate pages ( both in same directory otherwise edit page to the ajax target ) 作为2个单独的页面(都在同一目录中,否则将页面编辑到ajax目标)

<!doctype html>
<html>
    <head>
        <title>jQuery - ajax experiments</title>
        <script src='//code.jquery.com/jquery-latest.js'></script>

    </head>
    <body>
        <a id='link' role='button' href='#'>Test</a>
        <br /><br />
        <script>
            $('#link').click(function(e) {
                e.preventDefault();

                $.ajax({
                    url: 'jquery-ajax-target.php',
                    type: 'POST',
                    data: {
                        parameter1: 'test', 
                        parameter2: 'test2'
                    },
                    success: function(msg) {
                        alert( 'wow' + msg );
                    }
                });
            });
        </script>
    </body>
</html>

And the ajax target, jquery-ajax-target.php 还有ajax目标jquery-ajax-target.php

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();

        $parameter1=( isset( $_POST['parameter1'] ) ) ? $_POST['parameter1'] : false;
        $parameter2=( isset( $_POST['parameter2'] ) ) ? $_POST['parameter2'] : false;


        $_POST['modified']=array(
            'p1'=>sprintf('modified %s', strrev( $parameter1 ) ),
            'p2'=>sprintf('modified %s', strrev( $parameter2 ) )
        );


        $json=json_encode( $_POST );
        echo $json;

        exit();
    }

?>

Here is my version. 这是我的版本。 It will return a JSON response to your ajax which will be visible in your console for easy debugging. 它将对您的ajax返回JSON响应,该响应将在您的控制台中可见,以便于调试。

Your main page: 您的主页:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="link" role="button" href="#">Test</a>

<script>


$(document).ready(function(){

  $("#link").click(function(e) {
    e.preventDefault();
    console.log('function entered');
    $.ajax({
     url: "testPHP.php",
      type: "POST",
      dataType: 'json', //This tells your ajax that you are expecting a json formatted string as a response.
      data: {
        parameter1: 'test', 
        parameter2: 'test2'
      },
      success: function(msg) {
        console.log(msg); //This will show the results as an object in your console.

      }

    });
    console.log('Function End');
    //document.getElementById('#link').setAttribute('href','testPHP.php'); //Why are you doing this. It's not needed.
  });

});


</script>

Your testPHP.php page: 您的testPHP.php页面:

$results = array();

if(isset($_GET)){


  $results[] = array(

    'GET' => 'TRUE',
    'getData' => $_GET   

  ); 

}

if(isset($_POST)){

  $results[] = array(

    'POST' => 'TRUE',
    'postData' => $_POST   

  ); 

}

echo json_encode($results);

Here is an explanation of what is happening: 这是正在发生的情况的解释:

You make an initial call to your ajax by triggering some event. 您通过触发一些事件来对ajax进行初始调用。 In your case it is the click of the link. 您的情况是单击链接。

The click function leads to the actual ajax call which simply sends a post request to the testPHP.php . click函数导致实际的ajax调用,该调用仅将发布请求发送到testPHP.php

The testPHP.php receives the post request and performs some sort of operation with the data that was provided by the ajax call. testPHP.php接收发布请求,并使用ajax调用提供的数据执行某种操作。

The testPHP.php then sends back some sort of answer back to the ajax function. 然后, testPHP.php将某种答案发送回给ajax函数。 The data will be available in the success function. 数据将在成功功能中可用。

You then get to decide how to use the data that was passed back from the testPHP.php page to the success function. 然后,您可以决定如何使用从testPHP.php页面传递回成功函数的数据。

This is all done without your original page's code being refreshed. 无需刷新原始页面的代码即可完成所有这些操作。

You are not actually redirecting your user to another page.. You are just telling your page to goto another page and do some operation, which then gets reported back to the original page for you to do something with. 您实际上并没有将用户重定向到另一个页面。您只是在告诉您的页面转到另一个页面并执行一些操作,然后该操作将报告回原始页面供您执行操作。

Hope it helps. 希望能帮助到你。

It does work after removing type attribute on script tag. 删除脚本标签上的type属性后,它可以工作。 I am using <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> before main script tag. 我在主脚本标记之前使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> It is working here. 它在这里工作。 Also close the script tag. 同时关闭脚本标签。 I hope I can help. 希望我能帮上忙。 Also change the 同时更改

document.getElementById('#link').setAttribute('href','testPHP.php');

to

document.getElementById('link').setAttribute('href','testPHP.php');

The problem with your code is that you are using javascript to change the attribute and in javascript once you used getElementById you no longer have to use # sign. 代码的问题在于,您正在使用javascript来更改属性,而在使用getElementById javascript中,您不再需要使用#号。 try the following and it will work fine. 尝试以下方法,它将正常工作。

<?php

if(isset($_GET))
{
    echo "<script>alert('GET is there');</script>";
    print_r($_GET);
}
if(isset($_POST))
{
    echo "<script>alert('POST is there')</script>";
    print_r($_POST);
}
if(isset($_POST['parameter1']))
{
    echo "<script>alert('$_POST is set')</script>";
    header('Location: HomePage.php');
}
else
{
    echo "<script>alert('No post variable set')</script>";
}
?>
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</head>
<body>

<a id="link" role="button" href="index2.php">Test</a>

<script type="text/javascript">

    $("#link").click(function(e) {
        e.preventDefault();
        alert('function entered');
        $.ajax({
            url: "testPHP.php",
            type: "POST",
            data: {
                parameter1: 'test',
                parameter2: 'test2'},
            success: function(msg) {
                alert('wow' + msg);
            }

        });
        alert('function end');
        document.getElementById('link').setAttribute('href','testPHP.php');

    });
</script>
</body>
</html>

Furthermore it's a good practice to use the failed callback for the request. 此外 ,对请求使用failed callback是一种很好的做法。

 error: function (xhr, status, error) {
    alert(" Can't do because: " + error);
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM