更新
我试着看到更多的教程,我决定先使用$ .get(),因为它更容易,更有利于起点..
所以这是脚本,我认为它正常工作,除了它给出了未定义的结果
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Display Json</title>
<script src="../_js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#jsonButton').click(function()
{
var data = ''
$.get('getJson.php', data, response);
});//end click
});//end ready
function response(data)
{
$('#display').prepend('<p>' + data.name + data.phone + '</p>');
}
</script>
<body>
<div id="display">
<input type="button" id="jsonButton" value="getJson!" />
</div>
</body>
</html>
这是getJson.php简单的php脚本,它返回简单的JSON对象:
$data['name'] = 'username';
$data['phone'] = '08989808089';
header('Content-Type: application/json');
echo json_encode($data);
当我点击'getJson'按钮时,它会显示未定义的
答案 0 :(得分:3)
这是因为您的选择器不正确
$('submit').click(function()
//-^^^^^----here
应该是
$('input[name="submitButton"]').click(function(){
....
}
或者为您的按钮指定一个ID并使用带有#
<input type="submit" name="submitButton" value="getJson!" id="getjson"/>
$('#getjson').click(function(){
......
或者你可以使用
$('input:submit').click(function(){
.....
});
<强>更新强>
对于undefined,你可以调用回调函数.....
$.get('getJson.php', data, function(data){
$('#display').prepend('<p>' + data.name + data.phone + '</p>');
});
答案 1 :(得分:0)
您需要选择正确的按钮来绑定点击事件。
$('input:submit').click(function(){ });
答案 2 :(得分:0)
我不是100%确定你的选择权正确。我给按钮一个id并使用它。
<script type="text/javascript">
$(document).ready(function()
{
$('#mybutton').click(function()
{
$.ajax(
{
type: 'GET',
url: 'getJson.php',
dataType: 'json',
success: function(jsonData)
{
$('#display').prepend('<p>' + jsonData.name + ' ' + jsonData.phone + '</p>');
}
});//end ajax
return false;
});//end click
});//end ready
</script>
<body>
<div id="display">
<input id="mybutton" type="button" name="submitButton" value="getJson!" />
</div>
</body>
在这里阅读正确的jquery选择器
http://www.w3schools.com/jquery/jquery_ref_selectors.asp
您可以使用许多不同的选择器将click事件附加到该按钮。
编辑:将输入的类型更改为按钮...提交表单