weixin_33691817 2015-03-03 03:27 采纳率: 0%
浏览 19

未定义的返回ajax成功

here is my simple code in trying to get data from php to ajax. i just wanted to get a simple data pass back to ajax success. i already searched for this but i cant get it properly. my code is really simple.

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<SCRIPT TYPE="text/javascript">
$(document).ready(function(){
$("#1").click(function(){
$.ajax({
            type: "POST",
            url: "ajax.php",
            data: { "txt": "try"},
            cache: false,
            success: function(html)
            {                    
                 alert(html.mes);
            }
            }); 
});
});
</SCRIPT>
<pre><button id="1">try</button></pre>

Then i load a ajax.php that has a simple code too

$var['mes'] = 'message';
echo json_encode($var);

and its alerting me "undefined". i know this is simple but i cant find it out where do am i wrong

  • 写回答

1条回答 默认 最新

  • weixin_33737774 2015-03-03 03:31
    关注

    You need to tell jQuery that the script is running JSON:

    $(document).ready(function(){
        $("#1").click(function(){
            $.ajax({
                type: "POST",
                url: "ajax.php",
                data: { "txt": "try"},
                dataType: 'json',
                cache: false,
                success: function(html)
                {                    
                    alert(html.mes);
                }
            }); 
        });
    });
    
    评论

报告相同问题?