如何调用从php json编码传递的ajax数组? zend框架2

I can't call an arrays passed from the php json encode. I would concatenate 2 select state-contry-city. How can I do this??

This is the code:

I have 2 selects. I send the first value to an action:

php action into my controller:

  public function regioniProvinceComuniAction(){

         $response = $this->getResponse();
         $request = $this->getRequest();

         if ($request-> isPost()){
            $post_data = $request->getPost();
            $regione = (int)$post_data['regione'];
            $province = (int)$post_data['province'];                
         }

        if(isset($regione)){
            $prov = $this->getProvincia($regione);                
        }

         if(isset($province)){
            $com = $this->getComuni($province);                
        }

          $response->setContent(\Zend\Json\Json::encode(array('prov' => $prov, 'com' => $com)));
          return $response;    
     }

This is my js file:

  $("select#Regione").change(function () {
       var regione = $("select#Regione option:selected").attr('value');
       $.ajax({
           type: 'POST',
           url: '/zf-tutorial/public/regioni-province-comuni',
           datatype: 'json',
           data: { regione: regione },
           success: function (data) {

           alert (data);  
           }               
       });
  });

An example of the alert function is like this:

{"prov":[{"id":"10","nome":"Genova"},{"id":"8","nome":"Imperia"},{"id":"11","nome":"La Spezia"},{"id":"9","nome":"Savona"}],"com":[]}

I tried to populate my second select via data.post like this, but the values are "undefined":

success: function (data) { 
             $('select#Provincia option').each(function(){$(this).remove()});
             for(var i=0; i<data.length; i++){
                 $("select#Provincia").append('<option value="' + data[i].prov.id + '">' + data[i].prov.nome + '</option>');
             }

i tried to do

for (var i = 0; i < data.prov.length; i++) {
                    $("select#Provincia").append('<option value="' + data.prov[i].id + '">' + data.prov[i].nome + '</option>');
                }

if i set manually the var data, works fine, but with the response data doesn't work. i tried to do:

var prov = data.prov;
$("div#id").html(prov);

but it doesn't work. works only like this:

$("div#id").html(data);

and the output is the same

{"prov":[{"id":"10","nome":"Genova"},{"id":"8","nome":"Imperia"},{"id":"11","nome":"La Spezia"},{"id":"9","nome":"Savona"}],"com":[]}
查看全部
doutanggun9816
doutanggun9816
2014/09/25 15:03
  • json
  • php
  • ajax
  • javascript
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复