从MySQL数据库在JavaScript中使用获取数据
我有一个JavaScript动态生成HTML页面。在HTML页面中存在的信息已经存在于数据库中的文字区域框用户输入的信息。我想在mysql数据库中的数据库填充textarea的盒子。 我有PHP的code,将连接到数据库,并建立一个HTML表中的数据,所以我知道如何用PHP做到这一点,但我不知道如何从的javascrip做到这一点。我研究的AJAX GET请求,等等,但我仍然不知道如何做到这一点。
I have a javascript that dynamically builds an html page. In the html page there are textarea boxes for the user to type information in. The information already exists in a database. I would like to populate the textarea boxes with the database in the mysql database. I have php code that will connect to the database and build an html table with the data, so I know how to do this with php, but I don't know how to do this from the javascrip. I've studied ajax get requests, etc., but I'm still not sure of how to do this.
大概是最容易做到这一点是有一个PHP文件返回JSON的方式。因此,让我们假设你有一个文件 query.php
,
Probably the easiest way to do it is to have a php file return JSON. So let's say you have a file query.php
,
$result = mysql_query("SELECT field_name, field_value
FROM the_table");
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
$to_encode[] = $row;
}
echo json_encode($to_encode);
如果您正在受限使用的document.write(如您注意:在下面的意见),然后给你的领域,像这样一个id属性:<输入类型=文本ID =字段1 />
。您可以参考该领域与这个jQuery: $(#字段1)VAL()
If you're constrained to using document.write (as you note in the comments below) then give your fields an id attribute like so: <input type="text" id="field1" />
. You can reference that field with this jQuery: $("#field1").val()
.
下面是一个完整的示例的HTML。如果我们假设你的字段叫字段1
和域2
,然后
Here's a complete example with the HTML. If we're assuming your fields are called field1
and field2
, then
<!DOCTYPE html>
<html>
<head>
<title>That's about it</title>
</head>
<body>
<form>
<input type="text" id="field1" />
<input type="text" id="field2" />
</form>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$.getJSON('data.php', function(data) {
$.each(data, function(fieldName, fieldValue) {
$("#" + fieldName).val(fieldValue);
});
});
</script>
</html>
这就是HTML被构造之后插入,这可能是最简单的。如果你的意思是填充数据,而你动态地构造的HTML,那么你还是要PHP文件返回JSON,你只需直接将其添加到值
属性。