gpt4 book ai didi

javascript - promise 和上传数据

转载 作者:行者123 更新时间:2023-11-30 10:06:14 24 4
gpt4 key购买 nike

我在在线发送表格或在本地保存表格时遇到了一些问题。我有一个 Phonegap 应用程序,它只是一个简单的表单,可以保存到数据库中,或者如果失败,则保存到本地。

我只设置了这个功能。首先我想,我只是用 bool 值来做,运行函数,如果一切顺利,返回 True。但这行不通,因为代码只是在我有要比较的值之前执行,这意味着该值将始终为 false。

这是现在的代码:

if(uploadDataAndImage(formData))
{
//Its true, do my things
}
else
{
//Its false
}

这是 bool 函数:

function uploadDataAndImage(dataForm) {

var localURL = dataForm.cardurl;
console.log(localURL);

if(localURL == "")
{
$$.ajax({
type: "POST",
url: "upload.php",
crossDomain: true,
data: dataForm,
success:function(data)
{
console.log("Upload to server without card");
return true;
},
error: function()
{
console.log("Form couldn't upload to the server");
//alert("Couldnt upload to server, saving locally");
return false;
}
});

}
else{
//set upload options
var options = new FileUploadOptions();

options.chunkedMode = false;

console.log("Start upload picture");

var ft = new FileTransfer();
ft.upload(deLokaleURL, encodeURI("uploaderino.php"), win, fail, options);

function win(r) {
console.log("Code = " + r.responseCode);
console.log("R" + r.response);
console.log("Sent = " + r.bytesSent);

dataForm.cardurl = r.response;
var dataString = JSON.stringify(dataForm);



$$.ajax({
type: "POST",
url: "upload.php",
crossDomain: true,
data: dataForm,
success:function(data)
{
console.log("Upload to server with card");
return true;
},
error: function()
{
console.log("Form couldn't upload to the server, do nothing");
return false;

}
});



}

function fail(error) {
//alert("An error has occurred: Code = " + error.code);
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);


showMessage("Image upload has failed, get a better internet connection and try again!" , function(){console.log("Upload van de form is mislukt!")});
return false;

}
}



}

但这显然行不通。现在我做了一些研究并提出了 soem 问题,我找到了 Promises。但我似乎无法理解如何使用它。

我是这样想的:

var deferred = $.Deferred();

deferred.resolve(uploadDataAndImage(formData));

deferred.done(function(value) {
//Upload went well so do my things
});

但这不是它的工作原理,对吧/?

最佳答案

在 uploadDataAndImage 中使用 deferred 来返回一个 promise 。然后,当 ajax 调用完成时,您可以使用 then() 和 catch() 做一些事情。

function uploadDataAndImage() {
var deferred = $.Deferred();

$$.ajax({
type: "POST",
url: "upload.php",
crossDomain: true,
data: dataForm,
success:function(data) {
deferred.resolve();
}, error: function(e) {
deferred.reject(e);
}
});

return deferred.promise;
}

uploadDataAndImage(formData).then(function() {
//Its true, do my things
}).catch(function() {
//Its false
});

关于javascript - promise 和上传数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29010639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com