我使用的是codelgniter,vanilla javascript,ajex,css,MySQL only
我想设置存储在mySQL数据库中的图像的背景
下面的代码运行得很好&没有得到错误,但问题是我如何在数据库中设置图像存储的背景
注意,必须使用ajex(xhr请求响应(获取图像
javascript动态创建以下css
.demo0::before {
Background: URL ("path");
}
.demo1::before {
Background: URL ("path");
}
.demo2::before {
Background: URL ("path");
}
And so on
我有以下香草javascript
background_img=www.Demo.jpg; //temporary set
d_no=0;
Style0 = document.getElementByITagName("style")[0];
Style0.type="text/css";
Data=style0.innerHTML;
style0.innerHTML = data + "demo" d_no+"before { background: url("+ background_img +" );}";
d_no=d_no+1;
这很简单,但很棘手,你需要制作在css或javascript或html中获取img src/url值的控制器模型。url或src可能是路径或图像值
使用以下代码
控制器
<?php
class cover_img extends CI_Controller
{
public function index()
{
$getRequestData=stripslashes(file_get_contents("php://input"));
$datas=json_decode($getRequestData,true);
$this->load->model("cover_img_model","cim");
$this->cim->get_cover_img($datas["f_id"]);
}
}
?>
型号
<?php
class cover_img_model extends CI_Model
{
function get_cover_img($username)
{
// echo $username;
$data=$this->db->query("select cover from user_detail where user_name='$username'");
foreach ($data->result_array() as $row)
{
echo "data:image/jpg;charset=utf8;base64,";
echo base64_encode($row['cover']);
}
}
}
?>
香草javascript
style0=document.getElementsByTagName("style")[0];
style0.type="text/css";
ccs_data=style0.innerHTML+"n n";
xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost/CI-social-media/index.php/cover_img", false);
obj = {"f_id":f_id}; // f_id is primary key field value for get the img using where condition in mysql change this f_id dynamically for getting different img
// alert(f_id);
data = JSON.stringify(obj);
xhr.onload = () => {
if (xhr.status == 200) {
if (xhr.response) {
style0.innerHTML = ccs_data +"t "+ ".demo" + d_no + "::before{ ntt background: url('"+xhr.responseText+"'); nt} ";
// alert(xhr.responseText);
}
else {
alert("something want wrong try agin later")
}
}
else {
alert("Something Want Wrong Try agin");
}
}
xhr.send(data);
document.getElementsByTagName('head')[0].appendChild(style0);
d_no=d_no+1;
如果您从服务器获得二进制图像:
<script>
fetch("/image") // url of binary image response
.then((response) => response.blob())
.then((myBlob) => {
const objectURL = URL.createObjectURL(myBlob);
document.querySelector('#body') // element selector, which has background
.style.backgroundImage = `url(${objectURL})`
});
</script>
如果你有静态图像
<script>
fetch("/get-image.php") // url of php script, which returns url to static image
.then((response) => response.text())
.then((src) => {
document.querySelector('#body') // element selector, which has background
.style.backgroundImage = `url(${src})`
});
</script>