如何使用$ .getJSON从php文件中的JSON数据? [英] How to JSON data using $.getJSON from a php file?
问题描述
我有一个php文件,该文件从mySQL表接收数据. mySQL表"user_spec"只有一个字段选项",它返回.然后,我将返回的数据转换为JSON,下面是执行此操作的代码.
I have a php file that receives data from mySQL table. The mySQL table 'user_spec' has only one field 'options' that it returns. Then I convert returned data into JSON, under is code doing that.
<?php
$username = "user";
$password = "********";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect
to MySQL"); //print "Connected to MySQL<br>";
$selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");
$query = "SELECT * FROM user_spec";
$result=mysql_query($query);
echo json_encode(mysql_fetch_assoc($result));
?>
然后在HTML文件中,我尝试通过这段代码输出数据,但是它不起作用.我将非常感谢您的帮助.
then in an HTML file, I try to output data by this piece of code But it is not working. I will be very thankful for any help.
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function Preload() {
$.getJSON("Dhttp://localhost/conn_mysql.php", function(json){
alert("JSON Data: " + json.user_spec);
});}
</script></head>
<body onLoad="Preload()">
</body>
</html>
推荐答案
我认为不要使用文件地址:"D:xampp/htdocs/conn_mysql.php" ,您必须使用定义的网址由xampp提供,例如"http://localhost/mytest/conn_mysql.php"
I think instead of using the file adress: "D:xampp/htdocs/conn_mysql.php" you must use an url defined by xampp such as "http://localhost/mytest/conn_mysql.php"
您需要注意的另一件事是方法.顾名思义, $.getJSON ( http://api.jquery.com/jQuery.getJSON/)与GET方法一起使用.也许您应该尝试 $.post 或 $.ajax ( http://api.jquery.com/jQuery.post/).
Another thing you need to look out is the method. $.getJSON (http://api.jquery.com/jQuery.getJSON/), as its name says, works with the GET method. Maybe you should try $.post or $.ajax (http://api.jquery.com/jQuery.post/).
哦!并且要启动您的脚本,并非所有浏览器都支持< body onload =">.此外,它等待页面而不是DOM加载,这有时会给您脚本带来问题. 您应该使用 $('document').ready(function(),它等待DOM加载. 这样:
Oh! And to start your script, not all the browsers supports the <body onload="">. Furthermore, it waits for the page to be loaded, not the DOM, what can give you problems with your scripts sometimes. You should use $('document').ready(function(), that waits for the DOM to be loaded. This way:
<script type="text/javascript">
$('document').ready(function()
{
$.getJSON("D:xampp/htdocs/conn_mysql.php", function(json){
alert("JSON Data: " + json.options);
});
</script>
我希望它会有用! ^^
I hope it can be useful! ^^
这篇关于如何使用$ .getJSON从php文件中的JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!