简体   繁体   中英

ajax calls from php page - checking for an empty array as result

I have a php page which includes the following javascript:

<script>

$(document).ready(function(){
    $('#search').hide();
  });

$('#L1Locations').live('change',function(){

      var htmlstring;
      $selectedvalue = $('#L1Locations').val();

      $.ajax({
                url:"<?php echo site_url('switches/getbuildings/');?>" + "/" + $selectedvalue,
                type:'GET',
                dataType:'json',
                success: function(returnDataFromController) {
                    alert('success');
                        var htmlstring;
                        htmlstring="<select name='L2Locations' id='L2Locations'>";
                        htmlstring = htmlstring + "<option value='all'>All</option>";

                        console.log(returnDataFromController);


                         var JSONdata=[returnDataFromController];
                        alert('string length is' + JSONdata.length);
                        if(JSONdata.length > 0) 
                        {
                            for(var i=0;i<JSONdata.length;i++){
                            var obj = JSONdata[i];
                              for(var key in obj){
                                     var locationkey = key;
                                     var locationname = obj[key];
                                     htmlstring = htmlstring + "<option value='" + locationkey + "'>" + locationname + "</option>";
                                }
                             }

                            $('#l2locations').html(htmlstring);

                        }
                        else
                        {
                            alert('i think undefined');
                            $('#l2locations').html('');
                        }                           
               }

    });
 $('#search').show();
 });
</script>

what i'm trying to accomplish is dynamically show a combo box if the variable "returnDataFromController" has any items.

But I think I have a bug with the line that checks JSONdata.length.
Regardless of whether or not the ajax call returns a populated array or an empty one, the length always shows a being 1. I think I'm confused as to what is counted when you ask for the length. Or maybe my dataType property is incorrect? I'm not sure.

In case it helps you, the "console.log(returnDataFromController)" line gives the following results when i do get data back from the ajax call (and hence when the combo should be created)

[16:28:09.904] ({'2.5':"Admin1", '2.10':"Admin2"}) @ http://myserver/myapp/index.php/mycontroller/getbranches:98

In this scenario the combo box is displayed with the correct contents.

But in scenario where I'm returning an empty array, the combo box is also created. Here's what the console.log call dumps out:

[16:26:23.422] [] @ http://myserver/myapp/index.php/mycontroller/getbranches:98

Can you tell me where I'm going wrong?

EDIT:

I realize that I'm treating my return data as an object - I think that's what I want because i'm getting back an array. I guess I need to know how to properly check the length of an array in javascript. I thought it was just .length.

Thanks.

EDIT 2 : Maybe I should just chagne the results my controller sends? Instead of returning an empty array, should I return false or NULL?

        if (isset($buildingforbranch))
        {
                echo json_encode($buildingforbranch);  
        }
        else 
        {
            echo json_encode(false);
        }

EDIT 3:

Based on the post found at Parse JSON in JavaScript? , I've changed the code in the "success" section of the ajax call to look like:

                success: function(returnDataFromController) {

                        var htmlstring;
                        htmlstring="<select name='L2Locations' id='L2Locations'>";
                        htmlstring = htmlstring + "<option value='all'>All</option>";

                        console.log(returnDataFromController);


                         var JSONdata=returnDataFromController,
                            obj = JSON && JSON.parse(JSONdata) || $.parseJSON(JSONdata);
                            alert(obj);
 }

But i'm getting an error message on

[18:34:52.826] SyntaxError: JSON.parse: unexpected character @ http://myserver/myapp/index.php/controller/getbranches:102

Line 102 is:

obj = JSON && JSON.parse(JSONdata) || $.parseJSON(JSONdata);

The problem was that the data from the controller is malformed JSON.

Note the part of my post where I show the return data:

  ({'2.5':"Admin1", '2.10':"Admin2"})

The 2.5 should be in double quotes not single quotes. I don't understand how / why this is happening but I will create another post to deal with that question. Thanks everyone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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