使用Ajax和jQuery在表中显示图像
我正在使用AJAX向API发送请求,并使用包含图像名称和各种数据的JSON检索响应。
我试图将这些图像显示在HTML表中,但由于某些原因,仅显示图标未找到404 -IMG。
这是从AJAX响应中生成HTML的代码:
success : function(data){
$('#t tbody#search').empty();
if(data){
$('#t tbody#all').hide();
for (i = 0; i < data.length; i++) {
$('#t tbody#search').append('' +
'<tr><td> '+data[i].nom+' </td>' +
'<td>'+data[i].prix+' </td>' +
'<td>'+'<img src="{{asset('images/'~'+data[i].image +') }}"></td>'+
'<td>'+data[i].quantite+' </td>'+
'<td>'+data[i].descprod+' </td> </tr>');
};
}
有人可以解释发生了什么吗?
I am sending requests to an API using AJAX and retrieving a response with JSON containing image name and various data with it.
I am trying to display these images in a html table but for some reason only 404 - img not found
icons are displayed.
This is the code for generating the html from the AJAX response:
success : function(data){
$('#t tbody#search').empty();
if(data){
$('#t tbody#all').hide();
for (i = 0; i < data.length; i++) {
$('#t tbody#search').append('' +
'<tr><td> '+data[i].nom+' </td>' +
'<td>'+data[i].prix+' </td>' +
'<td>'+'<img src="{{asset('images/'~'+data[i].image +') }}"></td>'+
'<td>'+data[i].quantite+' </td>'+
'<td>'+data[i].descprod+' </td> </tr>');
};
}
Could someone explain what is going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这看起来像Laravel Blade语法:
但是该代码是由JavaScript驱除的。 Laravel/Blade并没有渲染此代码,因此在这里没有解释并转换为URI - 它只是JavaScript的文本,您最终将在
&lt; img src&gt; 。使用
您有几个选择来解决此问题:
如果数据来自的后端API是您自己的应用程序,则只需将其更新以包含对图像的完全合格的引用,因此您无需执行前端的任何东西。例如,后端添加了类似的东西:
然后在您的JavaScript中您可以做:
如果无法更新后端,则需要手动执行
Asset()
通常手动执行操作。 Asset基于asset_url >您有
.env
文件。所以说您的
Asset_url
是http://website/images/
;和一个示例
data [i] .image
isa4b0ee1ff531Edda05043231351231.jpeg
您可以在这样的JS中引用该内容:
如果此代码也在
http:// yourwebsite/
上运行,那么您甚至不需要该部分,您可以使用:This looks like Laravel Blade syntax:
But that code is being excecuted by Javascript. Laravel/Blade is not rendering this code, so that is not interpreted and converted into a URI here - it is just text to Javascript, and you'll just end up with that text in your
<img src>
. Use your browser's devtools and inspect the generated table, you will see this.You have a few choices to solve this:
If the back-end API where the data is coming from is your own application, just update it to include fully-qualified references to your images, so you don't need to do anything on the front end. Eg on the back end add something like:
Then in your Javascript you can just do:
If you can't update the back end, you need to do what
asset()
normally does manually. Asset generates a URL based on theASSET_URL
you have in your.env
file.So say your
ASSET_URL
ishttp://yourwebsite/images/
;And an example
data[i].image
isa4b0ee1ff5f531edda05043231351231.jpeg
Then you can reference that in JS like this:
If this code is also running on
http://yourwebsite/
, then you don't even need that part, you can just use: