[英]How to rewrite Ajax without using JQuery for my code
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. 嗨,我目前正在尝试将画布上的图像保存到数据库中,但是我的代码使用了不允许使用的jQuery。 Can someone please help me with an equivalent of this ajax command without using JQuery, here is my code: 有人可以在不使用JQuery的情况下通过等效的ajax命令来帮助我,这是我的代码:
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");})
});
You can use Native XMLHttpRequest Objects to accomplish this. 您可以使用本机XMLHttpRequest对象来完成此操作。 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 参考: https : //blog.garstasio.com/you-dont-need-jquery/ajax/#posting
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.