【问题标题】:php not receiving ajax post dataphp没有收到ajax post数据
【发布时间】:2014-05-03 20:53:30
【问题描述】:

我正在尝试通过 AJAX 将数据发送到 php 文件。我可以使用 GET 方法让它正常工作,但它不适用于 POST 方法(我的最终文件可能会变大,所以我想使用 POST)。

Javascript

函数更新表(){ var mydrop = document.getElementById('dropdown').value;

Request1 = new XMLHttpRequest();
if (Request1) {
    var RequestObj1 = document.getElementById('Target1');
    Request1.onreadystatechange = function () {
      if (Request1.readyState == 4 && Request1.status == 200) {
       // document.getElementById('Target1').innerHTML = "test"; 
        RequestObj1.innerHTML = Request1.responseText;
      }
    }

    Request1.open("POST", "table.php"); 
    Request1.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
//  var url = "table.php?brand="+mydrop;
//  Request1.open('GET', url);  // this works fine
    Request1.send("brand" + mydrop);
} // end Request1 function

}

我的 PHP

<?php
// header('Content-Type: text/xml')
ini_set('display_errors',1); 
 error_reporting(E_ALL);

 if(isset($_POST['brand'])) {
    $brandAccess = $_POST['brand'];

 }

 if(isset($_GET['brand'])) {
    $brandAccess = $_GET['brand'];

 }
print_r($_POST);
print_r($_GET);


include('./includes/connection.inc.php');
$conn = dbConnect();
$sql = "SELECT * from finished_goods WHERE BrandDesc LIKE '{$brandAccess}%' "; 

$result = $conn->query($sql);

?>

<table>
    <?php foreach ($result as $row) { ?>
    <tr>
        <td><?php echo $row['ProductNo'] ?></td>
        <td><?php echo $row['ProductName'] ?></td>
        <td><?php echo $row['BrandDesc'] ?></td>
        <td><?php echo $row['QtyOnHand'] ?></td>
    </tr>
    <?php } ?>
</table>

我把 print_r 函数放在那里只是为了仔细检查,无论我尝试什么,POST都是空的。

注意,我认为也许我需要 header('Content-Type: text/xml') 但是当我把它放进去时,页面根本不起作用。

谢谢,

【问题讨论】:

  • 请求是否出现在控制台中?试试Request1.send({ brand: "brand" + mydrop });

标签: javascript php ajax post


【解决方案1】:

试试

Request1.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Request1.send("brand=" + mydrop);

并在打印 $_POST 后设置死。 在 chrome dev-tools 中查看您对 php 进行了什么样的查询。

【讨论】:

  • 做到了,我不敢相信我错过了愚蠢 = 非常感谢
【解决方案2】:
you must forget the famous header ajax json for jquery or another
(only necessary for php but essenssial for a good response serveur)
<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);

**https://stackoverflow.com/questions/4064444/returning-json-from-a-php-script**

( if errors, you must write this first, before one echo html.. (and no echo html is good for great json response)

【讨论】:

  • 所以在我的情况下它会是 header('Content-Type: application/text');是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-23
  • 2016-10-17
  • 1970-01-01
相关资源
最近更新 更多