从ajax响应中获取图像src

我正在尝试使用带有ajax的php处理程序获取的图像路径来更改图像源。

我抓到的是:“img / blah.jpg”

这是我的ajax:

$('.name').click( function() { //var e = $(this).attr('src','img/no.png'); //this works $.ajax({ url:'handler.php?blahid='.$idnum, type:"GET", success: function(data) { var f = $(this).attr("src", data); //$(this) is the image I click on that I want to replace console.log(f); }, error: function(jqXHR, textStatus, errorThrow) { debugger; } }) } 

当我点击我想要改变的图像时,ajax就能完成它的工作。 也许我以不正确的方式使用响应数据。 我使用控制台日志来查看我得到的内容并返回了一个对象。 所以我想我的问题是:我现在正在做的事情不起作用,我不知道为什么。 如果您要我澄清任何事情,请告诉我。 提前致谢。

使用

 $('.publish').click( function() { var self=this; // add this line $.ajax({ url:'handler.php?blahid='.$idnum, type:"GET", success: function(data) { var f = $(self).attr("src", data); // use self instead of this console.log(f); }, error: function(jqXHR, textStatus, errorThrow) { debugger; } }); } 

试试这样吧

 var my_data = data; var f = my_data.find('img').attr("src"); 

或者你可以直接使用

 $(data).find('img').attr('src'); 

在你的例子$(this).attr("src", data); $(this)指向ajax请求。 要更改图像,您可以提供图像ID,如下所示$('#imageId').attr("src", data);

对于data-location-image,请确保在数据库中,例如http: http:// localhost / new_accemo_upd_1 / data / scan-yr-201 …

从添加数据:

 data.append('gambar', $('input[type=file]')[0].files[0]); 

保存数据(服务器)

 'gambar' : base_url($_FILES['gambar']) 

如果我们要编辑图片:

 $.ajax({ url : "/", type: "GET", dataType: "JSON", success: function(data) { $('[name="logo"]').attr("src", data.logo); }, error: function (jqXHR, textStatus, errorThrown) { alert('Error get data from ajax'); } }); 

查看HTML: