Javascript 如何在html中单击按钮时更改图像(每次来自服务器的img URL)

Javascript 如何在html中单击按钮时更改图像(每次来自服务器的img URL),javascript,jquery,html,Javascript,Jquery,Html,我对客户端脚本和stackoverflow都是新手。我想更改一个imageImage URL,它在每次单击按钮或锚定时都来自服务器。这是我更改图像的代码 $scope.captchaChange = function () { $http({ method: "POST", url: 'http://localhost:8080/Project/captcha/captcha', headers: { 'Conten

我对客户端脚本和stackoverflow都是新手。我想更改一个imageImage URL,它在每次单击按钮或锚定时都来自服务器。这是我更改图像的代码

$scope.captchaChange = function () {
    $http({
        method: "POST",
        url: 'http://localhost:8080/Project/captcha/captcha',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    }).success(function (response) {
        if (response.imgUrl.length > 0) {
            document.getElementById("captchaImg").src = response.imgUrl;
            document.getElementById("captchatext").value = response.imgToken;
        } else {
            alert('no captcha Image Avalable');
        }
    }).error(function (response) {
        //alert("response" + response)
        $scope.codeStatus = response || "Request failed";
        return false;
    });
}

假设您正在尝试从服务器加载新映像并替换div中的当前映像,可以这样做:

 $('#img-change-btn').click(function() {
    var path = response.imgUrl // Or some path;
    $('#img-display-div img').attr('src', path)
                         .attr('alt', $('img', this).attr('title')); 
});
以下是工作代码:


注意:我使用了一点JQuery。单击、.empty、.append等,如果不使用JQuery库,您可以删除它并仅使用Javascript。

如果我答对了您的问题,您想从服务器加载一个新图像并将其放入div中吗?我看到$scope、$http,如果您使用的是angular?用角的方法做way@Satpal是的,我正在使用它,但我对它还不熟悉,你能告诉我如何使用angularjs吗。感谢you@user3117914,也发布html模板是的,我检查过了,并没有错误,新图像的路径即将出现,但图像并没有被更改。empity函数工作正常,但append不正常。实际上,在运行tym的服务器端,我正在生成一个验证码图像,并发送该img的路径,并将该路径放入img的src属性中,但它不起作用。但是,如果我在服务器上对已经存在的映像执行相同的操作,那么其工作原理是:1.确保将URL发送到映像,而不是文件系统路径;2.在将URL发送到客户端JS之前,请确保图像已生成并存储在服务器上。嘿,Joshua,,,我已经完成了。。。。现在它的工作很好。。。这是服务器端的问题,每次我用相同的名称生成图像时,它都不会显示新图像,但现在每次我用不同的名称生成图像时,它都工作正常。。。谢谢你,库尔,不用谢我,为自己弄明白了这件事而拍拍自己的背:。