【问题标题】:html ajax post method returning null valuehtml ajax post方法返回空值
【发布时间】:2020-11-02 10:07:47
【问题描述】:

如何使用 ajax post 方法将 json 从 html 发送到 php?为了到达这里,我参考了this 和this,但我一直得到空返回值,其余类似的问题让我无处可去。

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;
?>

【问题讨论】:

  • 嗨,你能看看alert(response)给了什么吗?另外,你在哪里声明$reply?
  • $reply 在 $reply-> 上声明?我关注了w3schools.com/js/js_json_php.asp警报(响应);不工作

标签: php jquery json ajax


【解决方案1】:

调试的第一步是将您的 PHP 文件更新为如下内容:

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

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

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

$selectedUnit = $_POST["selectedUnit"];

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

【讨论】:

  • 所以...我如何在 php 中获取数据?
  • 刚刚尝试了您关于检索值的建议,警报消息不再起作用哈哈...没有尝试过var_dump...我可以知道如何使用它吗?试图将 var dump 回显到 div 中,但 div 没有显示任何更改
猜你喜欢
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-18
  • 2016-01-12
  • 1970-01-01
相关资源
最近更新 更多