html ajax post方法返回空值

时间:2020-11-02 10:07:47

标签: php jquery json ajax

如何使用ajax post方法将json从html发送到php?为了到达这里,我引用了thisthis,但由于返回的值一直为null,因此其他类似的问题都无济于事。

html(jquery ajax):

$('#unit1').change(function() {
var data = "";
  var selectedUnit1 = this.value;
  var dropDownNumber = "1";
  var postData = {"selectedUnit": selectedUnit1, "unitNumber": dropDownNumber};
$.ajax({
            type: "POST",
            dataType: "json",
            url: "ex02test.php",
            data: {data:postData},
            success: function(response){
                alert(response.title); // to test for return value, now it returns null, 
//hard-coding $unitTitle(example $unitTitle = 'hi'; in php file makes it display 'hi' so the php side is definitely working
                // data = jQuery.parseJSON(response);
                $('#txtHint').val(response[0].title);
            },
            error: function(e){
                console.log(e.message);
            }
    });
$('#totalcost').val(valueFUnction());
});

php:

<?php
$jsonData=$_POST["data"];

$data = json_decode($jsonData);

$unitCode = $data->selectedUnit;

$dropDownNumber = $data->unitNumber;

$unitTitle = $dropDownNumber;
$unitFee = "10";

$reply->title = $unitTitle;
$reply->fee = $unitFee;

$jsonReply = json_encode($reply);

header('Content-Type: application/json');
echo $jsonReply;
?>

1 个答案:

答案 0 :(得分:0)

调试此操作的第一步是将您的PHP文件更新为以下内容:

<?php
var_dump($_POST);
die();

然后您可以看到data变量中可能没有$_POST键,但是您的JSON内容直接发布到了POST正文中。

在这种情况下,我希望您可以使用以下方式检索PHP中的值:

$selectedUnit = $_POST["selectedUnit"];

但是请检查var_dump()的输出以查看发送到服务器的确切信息。

相关问题