简体   繁体   中英

how to get json/array from ajax responseText in to javascript array

I am using codeigniter in my project.When I am trying to get array element from encoded array, something id going wrong.How can I get encoded json array in my javaScript?

index.html

 <html> <head> <script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> function sendMessage(){ var message=document.getElementById('chatInput').value; var receverID=document.getElementById('id').value; if(message==''){ alert("please enter message"); } new Ajax.Request('index.php', { method:'get', evalJSON: true, parameters: { message: message, id: receverID }, onSuccess: function(transport){ var data= transport.responseText; console.log(data); }, onError: function() { alert('Error'); }, onComplete: function() { } }); } </script> </head> <body> <textarea name="chatInput" id="chatInput" cols="60" rows="3"></textarea><br /> <input type="button" name="send_message" onclick="sendMessage()" Value="Send"/> <input type="hidden" id="id" name="id" value="5"> </body> </html> 

index.php

 <?php header('Content-type: application/json'); $data['message'] = $_GET['message']; $data['sender_id'] = $_SESSION['id']; $data['user_id'] = $_GET['id']; $this->model_users->setMessage($data); echo json_encode($data); ?> 

Based on your comment, it seems that you have a HTML in your response. It's a good practice to put exit after json_encode call when you expect JSON response.

Try to put this in your index.php and it should works:

echo json_encode($data);
exit; // terminate the current script

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