已解决
问题解决了,请参阅我的解决方案的底部答案
我一直在努力解决这个问题,我阅读了有关$.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调用的'response'并获取:
Reload the page to get source for: http://localhost/Practice/Jquery/ajax/phone_data.php?rating=5&_=1368793325734
更新
我更新了我的代码,我搜索了一些来获取响应文本(使用来自responseText
的{{1}}属性),但它只是用空字符串警告(没有)。
这是我单独运行phone_data.php脚本时的输出:
response
来自firefox的和{"phone":"989898989","username":"sendyHalim"}
确认内容类型为"view page info"
答案 0 :(得分:1)
我复制粘贴你的代码并替换了json请求的url。
查看JSON URL。 http://echo.jsontest.com/key/value/one/two
我为html输出修改了一些jQuery代码。
$(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
}); //结束准备
这是你的代码: http://jsfiddle.net/wuaNC/
答案 1 :(得分:1)
<强>解决强>
伙计,这是我的错误哈哈!只是为了教育,如果你遇到与我相同的问题(脚本是正确的等等)......问题是我从本地文件中打开display_json.html
。这意味着我右键单击该文件,然后使用firefox打开。但是,当我通过localhost / pathToYourScript打开它时,它将运行。
我没有得到的一件事是,如果我使用指向另一个域的URL(如vincent的答案中的那个)从本地文件打开它,它可以工作,但是当我使用我的本地URL时,它不会“T
感谢您的提示和答案,你们真的帮了我。
答案 2 :(得分:0)
尝试为UTF-8全局编写脚本吗?