Jquery ajax不工作时返回PHP json_encode


jquery ajax does not working when returning with php json_encode

SOLVED

问题解决了,请看下面的答案

我一直在努力解决这个问题,我读了关于$.ajax()的教程

这是脚本

<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(
        function()
        {
            $('#getData').click(
                function()
                {
                    $.ajaxSetup({
                        cache: false
                    });
                    $.ajax(
                    {
                        type: 'GET',
                        url: 'http://localhost/Practice/Jquery/ajax/phone_data.php',
                        data: {rating: 5},
                        dataType: 'json',
                        success: function(data)
                        {
                            $('#display').html(data.phone);
                        },
                    error: function(response)
                    {
                        alert(response.responseText);
                    }
                    });//end ajax
                });//end click
        });//end ready
</script>
<body>
                <input type="button" id="getData" name="submitButton" value="getJson!" />
    <div id="display">
        replace me with phone data
    </div>
</body>

这是phone_data.php

<?php
header('Content-Type: application/json; charset=utf-8');
$data['phone'] = '989898989';
$data['username'] = 'sendyHalim';
echo json_encode($data, true);
exit();

当我点击按钮时,firebug显示请求是OK的,但是什么也没发生。

所以我通过firebug检查ajax调用的'response'并得到:

Reload the page to get source for: http://localhost/Practice/Jquery/ajax/phone_data.php?rating=5&_=1368793325734

我更新了我的代码,我搜索了一些方法来获得响应文本(使用responseText属性从response),但它只是警告空字符串(没有)。

下面是我单独运行phone_data.php脚本时的输出:

{"phone":"989898989","username":"sendyHalim"}

"view page info"从firefox确认内容类型为"application/json"

SOLVED

伙计们,这是我的错,哈哈!只是为了教育,如果你有和我一样的问题(脚本是正确的等等)…问题是我从本地文件打开display_json.html。这意味着我右键单击文件,然后用firefox打开。然而,当我通过localhost/pathToYourScript打开它时,它将运行。

我不明白的一件事是,如果我使用指向另一个域的url从本地文件打开它(就像vincent的答案中的url),它可以工作,但是当我使用我的本地url时,它不能。

谢谢你的提示和回答,你们真的帮了我大忙。

我复制粘贴了你的代码,并替换了json请求的url。

查看JSON URL。http://echo.jsontest.com/key/value/one/two

和jQuery代码,我修改了一些html输出。

$(document).ready(function () {
    
    $('#getData').click(function () {
        
        var jsonUrl = 'http://echo.jsontest.com/key/value/one/two';
        $.ajaxSetup({
            cache: false
        });
        $.ajax({
            type: 'GET',
            url: jsonUrl,
            data: {},
            dataType: 'json',
            success: function (data) {
                $('#display').html(data.one + ' and ' + data.key);
            },
            error: function(xhr){
                $('#display').html('error fetching data');
            }
        }); //end ajax
    }); //end click
}); //end ready
下面是你的代码:http://jsfiddle.net/wuaNC/

尝试将脚本全局化为UTF-8?