简体   繁体   English

如果没有返回的JSON数据,则使用AJAX成功函数

[英]AJAX Success function if there is no returned JSON data

I know this is simple but I am struggling to get this right. 我知道这很简单,但我正在努力做到这一点。 I am using jQuery/AJAX to retrieve some data (JSON) from my database. 我正在使用jQuery / AJAX从数据库中检索一些数据(JSON)。 I then have a success function to display the data. 然后,我有一个成功函数来显示数据。 This works fine but I want to have alert the user if there are no returned results. 这工作正常,但如果没有返回结果,我想提醒用户。

My PHP excerpt which encodes the JSON: 我的PHP摘录,它编码JSON:

...

while($row = $result->fetch_all())
{
    $returnResult = $row;
}
echo json_encode(['result' => $returnResult, 'errors' => $errors]);

....

My JSON data format looks like this: 我的JSON数据格式如下所示:

{"result":[["Grade 12","Studies","John","Doe"]],"errors":false}

My jQuery that then uses the JSON data and displays in html elements: 然后,我的jQuery使用JSON数据并显示在html元素中:

function getworkload(){

        $.ajax({
        type: "POST",
        url: "modules/getworkload.php",
        dataType: 'json',
        data: {id:id},
        cache: false,
        })
        .success(function(response) {
            if(!response.errors && response.result) {
                $.each(response.result, function( index, value) {
                    $("#divwork").append('<li class="list-group-item"><b>'+value[0]+'</b> : '+value[1]+'</li>');
                    $("#spnname").html('<b>'+value[2]+' '+value[3]+' Workload </b>');
                });
            } else {
                $.each(response.errors, function( index, value) {
                    $('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
                });
            }
        });
}

I have tried to replace if(!response.errors && response.result) { with the following: 我试图用以下内容替换if(!response.errors && response.result) {

  1. if(!response.errors && response.result=null) {
  2. if(!response.errors && !response.result) {
  3. if(!response.errors && response.result.length < 1) {

而不是在JSON中传递错误false,而是抛出404或500之类的HTTP错误代码。然后,您可以在JavaScript中放置一个error部分,而不是在success部分中进行检查。

Assuming the returned JSON is as follow, 假设返回的JSON如下所示,

{"result":[["Grade 12","Studies","John","Doe"]],"errors":false}

You just have to put one condition to check if the result length is 0 or not. 您只需要放置一个条件即可检查result长度是否为0

Like this, 像这样,

if(!response.errors && response.result) {
                $.each(response.result, function( index, value) {
                    $("#divwork").append('<li class="list-group-item"><b>'+value[0]+'</b> : '+value[1]+'</li>');
                    $("#spnname").html('<b>'+value[2]+' '+value[3]+' Workload </b>');
                });
            } else if(!response.errors && response.result && response.result.length==0) {

                 // Handle 0 result output here...

            } else {
                $.each(response.errors, function( index, value) {
                    $('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
                });
            }

your code is not correctly parsing json value from php file to javascript and you have to parse json before using in javascript 您的代码无法将php文件中的json值正确解析为javascript ,因此您必须先解析json然后才能在javascript使用

  function getworkload(){

        $.ajax({
        type: "POST",
        url: "modules/getworkload.php",
        dataType: 'json',
        data: {id:id},
        cache: false,
        })
        .success(function(response) {
            console.log(response);
             var  res = JSON.parse(response);
           console.log(res);/* console json val*/
            if(!res.errors && res .result) {
                $.each(res.result, function( index, value) {
                    $("#divwork").append('<li class="list-group-item"><b>'+value[0]+'</b> : '+value[1]+'</li>');
                    $("#spnname").html('<b>'+value[2]+' '+value[3]+' Workload </b>');
                });
            } else {
                $.each(res.errors, function( index, value) {
                    $('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
                });
            }
        });
}

Let the server return the word 'nothing' for example in case of no result and split the code to three cases if result and if error and if nothing 让服务器在没有结果的情况下,例如返回单词“无”和代码分割到三个案例,如果结果,如果错误,如果没有

if(isset($returnResult) && $returnResult!=null){
echo json_encode('result' => $returnResult);
}
else if (isset($errors) && $errors!=null){
echo json_encode('errors'=>$errors);
}
else { echo "nothing";}

Check that response is not nothing on success function 检查成功功能上的响应是否正确

.success(function(response) {
if(response=='nothing'){
alert('nothing');
}
else {
//rest of the success function
}

Another suggestion is to use this if statement with in success function 另一个建议是在成功函数中使用此if语句

.success(function(response) {
if(!response.result && !response.errors){
alert('nothing');
}
else {
//rest of the success function
}

Or 要么

.success(function(response) {
if(response.result==null && response.errors==null){
alert('nothing');
}
else {
//rest of the success function
}

In your PHP script change your echo json_encode... to 在您的PHP脚本中,将echo json_encode...更改为

 echo json_encode(['result' => (count($returnResult)) ? $returnResult : 0, ...]);

Then in your JS simply do 然后在您的JS中做

if(!response.errors && !!response.result) {...

只需在第一行在success()中使用JSON.parse(responce) ,然后使用它即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM