donglv9116 2018-11-22 22:49
浏览 82

如何在不使用JQuery代码的情况下重写Ajax

Hi I am currently trying to save an image on my canvas to my database, but my code uses jQuery of which I am not allowed to. Can someone please help me with an equivalent of this ajax command without using JQuery, here is my code:

document.getElementById('save').addEventListener('click', function()
var canvas = document.getElementById("canvas");
var dataUrl = canvas.toDataURL("image/png");
$.ajax(
{
type: "POST",
url: "../webcam/save_image.php",
data: {image: dataUrl}
})
.done(function(respond){console.log("done: "+respond);})
.fail(function(respond){console.log("fail");})
.always(function(respond){console.log("always");})
});
  • 写回答

1条回答 默认 最新

  • douhuifen9942 2018-11-22 23:25
    关注

    You can use Native XMLHttpRequest Objects to accomplish this. I believe your code should look something like this, I haven't tested it though, so you will need to tweak it somewhat I'm sure.

    document.getElementById('save').addEventListener('click', function()
    var canvas = document.getElementById("canvas");
    var dataUrl = canvas.toDataURL("image/png"), xhr = new XMLHttpRequest();
    
    
    xhr.open('POST', '../webcam/save_image.php');
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        if (xhr.status === 200 && xhr.responseText !== dataUrl) {
            console.log('fail');
        }
        else if (xhr.status !== 200) {
            console.log('fail');
        }
    };
    xhr.send(encodeURI('url=' + dataUrl);
    

    Reference: https://blog.garstasio.com/you-dont-need-jquery/ajax/#posting

    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入