【发布时间】: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警报(响应);不工作