问题
I have the following script:
$("#spid").blur(function() {
$.ajax({
url: 'getsponsor.php',
type: "POST",
dataType:'json',
data: ({ spid: $("#spid").val() }) ,
contentType: 'application/json; charset=utf-8',
success: function (result) {
$("#sponname").text(result);
},
error: function () {
$("#sponname").text("Cannot fetch the sponsor name.");
}
});
});
Note: #sponname is a label tag.
Following is the php code of getsponsor.php:
if(!isset($_POST['spid']) || empty($_POST['spid']))
echo json_encode("No Data");
else {
$spid=$_POST['spid'];
$stmt = $con->prepare("SELECT name FROM users WHERE id=?");
$stmt->bind_param("s",$spid);
$stmt->execute();
$stmt = $stmt->get_result();
if ($stmt->num_rows >0) {
$row = $stmt->fetch_object();
echo json_encode($row->name);
}
else {
echo json_encode("No Records");
}
}
When I Inspect the page and goto Network->Params, I get the right value from the textbox:
spid=1125468
But, when I go to Network->Response, I get the following message
"No Data"
Please tell what wrong I am doing?
回答1:
Get rid of this line:
contentType: 'application/json; charset=utf-8',
The data is being sent URL-encoded, not as JSON. jQuery will send the correct Content-type header by itself.
来源:https://stackoverflow.com/questions/52111576/jquery-ajax-params-has-data-but-response-says-no-data