基本上我想通过从 mysql 数据库中获取数据来更改图像的“src”属性。
我有一个 query.php 文件和 index.html 文件。
query.php 文件中的 php 脚本工作正常并获取正确的数据,这些数据现在保存在一个名为
的 php 变量中$newimagesrc
现在我如何使用 javascript 更改图像的“src”(我猜)?我必须在一份文件中实现所有内容吗?这个想法是显示图像,然后通过单击按钮重新加载页面并显示新图像。
谢谢!
我的 html 文档:
<html>
<head>
</head>
<body>
<img src="" alt=changingimage">
</body>
</html>
我的 php 文档:
// mysql_connect stuff right here
// QUERY FOR NEW IMAGE
$imagequery = "SELECT * FROM images ORDER BY rand() LIMIT 1";
$result = mysql_query($imagequery);
while($row = mysql_fetch_object($result))
{
$newimagesrc = "$row->imageurl";
}
最佳答案
下面是一些实现它的示例代码:
在用户端,您创建一个 XHR(我将使用 jquery XHR,因为它的演示行较少,但您可以使用任何 XHR 包装器甚至原始对象本身)
$.get('/path/to/query_script.php', { perhaps: 'you', need: ['some', 'data', 'sent', 'to', 'the', 'server'] }, function (data) {
// Select the image somehow and apply the data you just received
$('#myImage').attr('src', data);
});
而在 php 端,你会有这样的东西:
// Your code to fetch the source here..
header("Content-Type: text/javascript; charset=utf-8");
echo(json_encode($newimagesrc)); // Encodes your data in a json format and hopefully sends that as *the only thing* in the response
这里要意识到的一般事情是,您正在指导两个不同参与者之间的通信 - 一个运行您的 javascript 代码的浏览器和一个运行您的 php 代码的服务器。浏览器需要向你的服务器发送一个请求(这里使用 XHR 解决),服务器必须返回一些有用的响应(这里通过以方便的 json 格式返回图像源来实现)。您可以扩展它以返回多个字符串(您可以以 json 格式序列化数组和整个对象),并因此在客户端使用数据。
关于javascript - 从 mysql 查询设置的 php 变量更改图像的 'src' 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21645293/