【发布时间】:2013-05-12 14:53:40
【问题描述】:
已解决
问题已解决,请参阅我的解决方案的底部答案
我一直在努力解决这个问题,我阅读了有关 $.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 显示请求正常,但没有任何反应..
所以我通过 firebug 检查 ajax 调用的“响应”并得到:
Reload the page to get source for: http://localhost/Practice/Jquery/ajax/phone_data.php?rating=5&_=1368793325734
更新
我更新了我的代码,我搜索了一些方法来获取响应文本(使用来自response 的responseText 属性),但它只是用空字符串(什么都没有)发出警报。
这是我单独运行 phone_data.php 脚本时的输出:
{"phone":"989898989","username":"sendyHalim"}
和来自 firefox 的 "view page info" 确认内容类型是 "application/json"
【问题讨论】:
-
在你的 AJAX 调用中添加一个
error回调函数,看看 jQuery 报告了什么错误。 -
您应该能够在 Firebug 的控制台选项卡中看到响应,而无需重新加载。
-
您能否打印打开 JSON 文件时在浏览器中看到的内容?
-
@AnthonyGrist 我用函数更新了我的代码以显示错误,但它什么也没显示.. 来自控制台选项卡的@JayBlanchard,控制台选项卡中没有响应(响应部分)@imsiso 我无论如何都做不到它不是json文件,在我这样做之前(上面的脚本)我一直在使用
$.get,当我显示json响应时,它显示未定义(使用相同的php脚本) -
顺便说一句,你不需要
header('Content-type: application/json');并添加exit();最后在echo json_encode..之后尝试