How to handle empty return from getJSON
Alright so I have a php script which gets results from a DB, and to get those res开发者_运维知识库ults I'm using a jQuery script to pull the results via getJSON. It works perfectly but now I want to do something if the php script returns no results (empty).
I tried:
$.getJSON('path/to/script'), {parameter:parameter}, function(data){
if (data) {
alert('Result');
} else {
alert('Empty);
}
});
But it's no good. I've tried different things like if (data.length) but still nothing. I've noticed that if there is no returned data the callback will never fire at all. So if that's the case, how do I handle a empty return?
You should check your PHP output to always output some data.
In my codes I add a success flag to my outputs, like this:
$result = array (
'success' => true,
'data' => $data
);
echo json_encode($result);
If I don't output anything, I put false into success, which makes it easy to validate in jQuery via data.success:
Example:
$.getJSON('path/to/script', {parameter:parameter}, function(data){
if (data.success) {
alert('Result');
} else {
alert('Empty');
}
});
If you don't want to modify your output, you can setup an ajaxError to catch your reading problems.
Example:
$.ajaxError(function() {
alert('error triggered');
});
P.S.: I dont know if the missing ' at the end of this line:
alert('Empty);
is really missing in your original, if so, your missing a ' ;-) >>
alert('Empty');
$.getJSON('json.php?',function(r){
try {
typeof(r[0].city);
} catch (e) { return false; /* or do somthing */ }
[...]
According to the documentation, if you get nothing on the response, .getJSON
will give you null
. However, if you're passing something such as {}, you will end up with an object
that has no such properties as .length
and that will be regarded as true
in an if
condition.
If you need to identify an empty object, there may be a shorter way, but the one that occurs me at the moment is:
var isEmpty = true;
for (var p in data) { isEmpty = false; break; }
// at this point, if isEmpty should tell you if 'data' is an empty object
This poor code works assuming that data
is of type object.
Here is how I handle empty responses in JS getting data from PHP!
response.php
if (check parameters from script.php) {
$result = $con->query(sqlAll($con)); // 'sqlAll()' returns a query like 'SELECT * FROM table'
$arrData = array(); $i = 0; $tot = array(); $empty = ''; // '$empty' we'll use for empty response
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
// fill array
$arrData = array (
'title' => $row["post_title"],
'author' => $row["post_author"]
);
$tot[$i] = $arrData; // collect data from '$arrData'
$i++;
}
// tell PHP to become 'JSON-MASTER'
header('Content-type: application/json');
echo json_encode($tot); // transfer response to script.php
}
else echo json_encode($empty);
script.php
$('#search_txt').keyup(function(){ // instant search
$.getJSON('response.php', {
// some parameters to be sent
},
function(data){
var row = "";
$.each(data, function(key, val) {
row +=
'<h2>'+
'<a href="#">'+val.title+
'</a></h2>'+
'<p class="lead">'+
'by <a href="index.php">'+val.author+'</a>'+
'</p>';
});
$('.box').html(row); // display result to the page
}
)
});
This worked for me:
return json_encode([]);
As a result, the jQuery success handler saw the response as an empty array:
$.getJSON("/url", function(data) {
console.log("data.length: " + data.length); // data.length: 0
}
精彩评论