简体   繁体   中英

How to decode array response from php to jquery ajax?

I have PHP function:

public function doit()
{
    $arr1= array();
        $arr1['index1'] = 'value1';
            $arr1['index2'] = 'value2';
}

I call it from my JQuery function:

$.ajax
({    
    url: "/controller/doit",  
    success: function()
    { 
        alert('done!'); 
    }  
 });  

Everything I want is - that my JQuery function, which contains this ajax call will return me the array, which is identical to the one, which PHP function returned (the only difference is language of course: JS instead of PHP)

You need to return something from your doit function.

public function doit()
{
  $arr1= array();
  $arr1['index1'] = 'value1';
  $arr1['index2'] = 'value2';

  echo json_encode($arr1);
}


$.ajax
({    
  url: "/controller/doit",  
  success: function(data)
  { 
    console.log(data); 
  }  
});  

Edit:

Jquery to PHP: When the javascript is run, it will send the data array to the server using the url. The server receives the array, encodes it as json and sends it back to the success callback function which will log the data to the console.

// YOUR JAVASCRIPT FILE
// your data to send.
var data = {'index1': 'value1', 'index2': 'value2'};

$.ajax({
  type: 'POST',
  url: '/controller/doit',
  data: data,
  success: function(data) { console.log(data) },
  dataType: 'json'
});


//YOUR PHP FILE
public function doit()
{ 
   // you should be setting your content type header to application/json if sending json
   header('Content-type: application/json');
   echo json_encode($_POST['data']);
}

You can echo the array as json from php using:

echo json_encode($arr1);

And use $.getJSON in your JS:

$.getJSON('/controller/doit', function(data) {
  console.log(data);
});

you can use JSON to encode your array. http://php.net/manual/en/function.json-encode.php

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