问题
i have to get output in this format
var sampleTags = ['c++', 'scala'];
My javascript function is:
<script>
$(document).ready(function(){
$(function(){
var sampleTags;
$.ajax({
url:"<?php echo base_url('ajax_get_tags/gettags'); ?>"
}).done(function(data) {
if (data) {
sampleTags = data;
}
});
......................
.......................
$(function(){
var sampleTags = <?php echo json_encode($query) ?>;
My php controller is
function gettags(){
$json_array=$this->tagsmodel->get_all_tags();
echo json_encode($json_array);
}
My model is
//-------------------------------Function get all tags--------------------------------
function get_all_tags() {
$this->load->database();
$this->db->limit('10');
$this->db->select('tags_name');
$res = $this->db->get('tags');
$ret = array();
foreach ($res->result_array() as $row) {
$ret[] = $row['tags_name'];
}
return $ret;
}
How can get the json output from ajax request to be display its value for a javascript variable? Please help me to solve this issue..
回答1:
You're using an older version of jQuery, so .done
won't work. It looks like you want to add a key to your request object called complete
, with the anonymous function as its value:
$.ajax({
url: "<?php echo base_url('ajax_get_tags/gettags'); ?>",
complete: function(data) {
if (data) {
sampleTags = data;
}
}
});
I found this out by googling your error message. One of the results was this question: Object #<XMLHttpRequest> has no method 'done'. You could have just googled the error message and figured this out yourself.
回答2:
I would like to give a few suggestions
- Check for the return value form the server side by printing it with die or exit.
- check the http response in firebug net tab. 3.
来源:https://stackoverflow.com/questions/16441838/php-unable-to-get-the-json-output-into-my-javascript-page-as-a-variable-value