我只使用 codelgniter、vanilla javascript、ajex、css、MySQL
我想設定存盤在 mySQL 資料庫中的影像背景
以下代碼運行良好且沒有出錯,但問題是如何在資料庫中設定影像存盤的背景
請注意,必須使用 ajax 獲取影像(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;
uj5u.com熱心網友回復:
如果您從服務器獲取二進制影像:
<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>
uj5u.com熱心網友回復:
這很簡單但很棘手,您需要制作在 css 或 javascript 或 html url 或 src 中獲取 img src/url 值的控制器模型可能是路徑或影像值
使用以下代碼
控制器
<?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{ \n\t\t background: url('" xhr.responseText "'); \n\t} ";
// 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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/514617.html
上一篇:htaccess將所有內容從子檔案夾重定向到另一個域
下一篇:作曲多個專案?
