使用ajax或ajax(json)将数据发布到同一页面中的php

时间:2017-02-07 18:27:06

标签: php jquery json ajax post

我正在尝试邮件申请。我的目标是通过点击一个按钮获取发件人ID和接收者ID。 之后用ajax或ajax(json)将这些数据发布到同一页面的php中。

我将使用php中的传入数据和mysql_query。我尝试了很多例子。但永远不会得到结果。我的示例代码如下所示。

小注意:成功提醒但不会在屏幕上打印任何数据。



<html>
<head>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
  <body>
    <button type="button" onclick="myFunc()">Get ID</button>
    <script>
    function myFunc()
    {
    var id = 'example';
    jQuery.ajax({
        url:'index.php',
        type: "POST",
        data: {'name':id},
        success: function(data)
            {
               alert("success");
            }
    });
    };
    </script>
   <?php
   if(isset($_POST['name']))
   {
      $value = $_POST['name'];
      echo $value;
   }
   else
   {
      echo "don't work.";
   }
   ?>
  </body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
<?php
   if(isset($_POST['name']))
   {
      echo json_encode(array(
        'value' => $_POST['name']
      ));
      exit();
   }
?>

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
  <body>
    <button type="button" onclick="myFunc()">Get ID</button>
    <script>
    function myFunc()
    {
    var id = 'example';
    jQuery.ajax({
        url:'index.php',
        type: "POST",
        data: {'name':id},
        dataType : 'json', 
        success: function(data)
            {
               alert("success");
            }
    });
    };
    </script>

  </body>
</html>
&#13;
&#13;
&#13;