如何从ajax responseText获取json / array到javascript数组

时间:2015-10-28 09:07:10

标签: javascript php jquery json ajax

我在我的项目中使用codeigniter。当我尝试从编码数组中获取数组元素时,出现了错误。如何在javaScript中获取编码的json数组?

的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>
&#13;
&#13;
&#13;

的index.php

&#13;
&#13;
<?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);
?>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

根据您的评论,您的回复中似乎有HTML。当您期望JSON响应时,在exit调用之后放置json_encode是一个很好的做法。

尝试将其放入index.php,它应该有效:

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