我刚刚开始学习如何使用JSON,但在一个非常简单的页面上遇到了麻烦。
我试图将数字传递给PHP,将其添加到数据库中,并检索(有些随机 )数组以显示在信息div中。来自文本框的文本确实被成功输入到了数据库,但是,我没有从JSON编码数组中获得任何返回信息。
<?php
include_once('functions.php');
if (isset($_GET['number'])){
$num = $_GET['number'];
dbQuery("INSERT INTO `wheels` (`wheelNo`) VALUES ($num);");
$blah = Array();
$blah['item1'] = 'hats';
$blah['item2'] = 'shoes';
echo json_encode($blah);
}
?>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#sub').click(function(){
var num = $('#num').val();
$.getJSON('test.php','number='+num, function(data) {
$('#info').html(data.item1);
});
});
});
</script>
</head>
<body>
<button id="sub">Submit</button>
<input type="text" id="num" />
<div id="info">
</div>
</body>
</html>
At the moment your HTML will be tacked on to the end of your JSON causing it to be invalid, try calling exit()
immediately after json_encode()
to make sure nothing else is printed to the page.
to stop the reading of the code after the echo json_encode($blah);
try to type die();
thereafter