关于javascript:如何使用AJAX将数据发布到php文件

How to POST data to php file using AJAX

本问题已经有最佳答案,请猛点这里访问。

我无法将数据发送到要处理的PHP文件。我试过了几乎所有的方法,但找不到问题的根源。下面是一个php文件,它在用户单击购买按钮后将产品名称、价格和ID发送到checkout函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php

      $servername ="localhost";
      $username ="root";
      $password ="root";
      $dbname ="Test";

        // Create connection
      $conn = new mysqli($servername, $username, $password, $dbname);

        // Check connection
      if ($conn->connect_error) {
       die("Connection failed:" . $conn->connect_error);
     }

     $sql ="SELECT P1.Product_Name, S2.Price, P1.Product_ID FROM Product P1, Sale_Item S2 WHERE P1.Product_ID=S2.Product_ID AND P1.Category='Sports'";
     $res = $conn->query($sql);
     $counter=0;

     while ($row = $res->fetch_assoc()){

      $Product_Name = $row["Product_Name"];
      $Price = $row["Price"];
      $Product_ID = $row["Product_ID"];

      echo ('<td><p>

</p>'
.$row["Product_Name"].''.$row["Price"].'<p>

</p><input type="button" value="Buy" onclick="checkout(\''
. $Product_Name . '\', \'' . $Price . '\', \'' . $Product_ID . '\')"</td>');          
      $counter++;

      if ($counter==3) {
        $counter=0;
        print"";
      }
    }

    $conn->close();
    ?>

接下来是checkout函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script type="text/javascript">
        function checkout(Product_Name, Price, Product_ID) {
          //document.write(Product_Name, Price, Product_ID)
          var theProduct_Name = Product_Name;
          var thePrice = Price;
          var theProduct_ID = Product_ID;

          $.ajax({
            type:"POST",
            url:"http://localhost:8888/checkout.php",
            data: {Product_Name: theProduct_Name, Price: thePrice, Product_ID: theProduct_ID},
          });

          window.location.assign("http://localhost:8888/checkout.php")
        }

我正在使用妈妈的phpmyadmin数据库。我的网址不正确吗?我试过用"http://localhost:8888/checkout.php"checkout.php。下面是我需要处理数据的PHP文件。为了简单地学习如何发送数据,我只是在文件中回响,以确保它实际上是发布的。但没有什么能得到回应。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php

  session_start();
  $servername ="localhost";
  $username ="root";
  $password ="root";
  $dbname ="Test";

  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);

  // Check connection
  if ($conn->connect_error) {
   die("Connection failed:" . $conn->connect_error);
 }

  $theProduct_Name = $_POST['Product_Name'];
  $theProduct_ID = $_POST['Product_ID'];
  $thePrice = $_POST['Price'];

 echo $theProduct_Name.$theProduct_ID.$thePrice;

 ?>

我对网络编程是个新手,因此任何帮助或提示都会受到赞赏。我已经看了好几个小时了,似乎不能让它工作。


When using Ajax, the request is sent by ajax and you can see the response in the success method. Any direct call to the action URL will sends new request which is empty in this case for the line

1
window.location.assign("http://localhost:8888/checkout.php")

删除这一行代码并更改jquery.ajax,如下所示,查看响应是什么。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var request = $.ajax({
    type:"POST",
    url:"http://localhost:8888/checkout.php",
    data: {Product_Name: theProduct_Name, Price: thePrice, Product_ID: theProduct_ID},
    dataType:"html"
});

request.done(function(msg) {
  alert ("Response:" + msg );
});

request.fail(function(jqXHR, textStatus) {
  alert("Request failed:" + textStatus );
});


我测试了您的代码,它运行正常,Ajax请求正常发生,请尝试从您的javascript代码中删除这一行。window.location.assign("http://localhost:8888/checkout.php");

我使用jquery的这个版本:https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js

在Google Inspector的"网络"选项卡中,我可以看到:

1
2
3
4
5
6
7
8
Request:
Request URL:http://localhost:8888/checkout.php
Request Method:POST
Status Code:200 OK
Remote Address:127.0.0.1:8888

Response:
Bike150


You can track the ajax request in browser console. It will show you the request and response and the error you are receiving from your php script.
If on button click you are not able to see any request in the console then try to use"method" instead of"type". Some older jquery version doesn't support type. method:"POST",


您应该对代码进行以下更改

[cc lang="javascript"]$.ajax({
method:"POST",
url:"http://localhost:8888/checkout.php",
data: {"Product_Name":"theProduct_Name","Price":"thePrice","Product_ID":"theProduct_ID