我正在使用对 Web 服务的 AJAX 调用检索服务调用列表。我需要遍历 Web 服务返回的每个服务调用并将其插入到 SQLite 表中。我正在努力解决循环中的时间问题。例如,如果有两个服务调用,两行将插入到表中,但都是来自第二个调用的数据。我尝试移动我的变量声明和值分配,如果它们在事务中,那么所有字段都返回未定义。在事务和所有行之外插入作为最后一条记录。
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "MyService.asmx/GetCalls",
data: '{ user:"' + user +'"}',
success: function (data) {
saveCalls(data.d);
},
error: function (xhr) {
var err = eval("(" + xhr.responseText + ")");
alert("Retrieve Calls: " + err.Message);
}
});
function saveCalls(result) {
var insertString = "Insert Into Calls Values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
var call, po, adrsCode, status, dispDate, dispTime, desc, customer, address, city, state, zip, phone, equipment, tracking, srvType, statDesc;
$.each(result, function () {
call = this.CallNumber;
po = this.PoNumber;
adrsCode = this.AdrsCode;
status = this.Status;
dispDate = this.DispatchedDate;
dispTime = this.DispatchedTime;
desc = this.Description;
customer = this.Customer;
address = this.Address;
city = this.City;
state = this.State;
zip = this.Zip;
phone = this.Phone;
equipment = this.Equipment;
tracking = this.Tracking;
srvType = this.SrvType;
statDesc = this.StatDesc;
db.transaction(function (tx) {
tx.executeSql(insertString, [call, po, adrsCode, status, dispDate, dispTime, desc, customer, address,
city, state, zip, phone, equipment, tracking, srvType, statDesc],
onSqlSuccess, onSqlError);
});
});
}
编辑:适用于有同样问题的人的代码:
function saveCalls(result) {
var insertString = "Insert Into Calls(CallNumber, PoNumber, AdrsCode, SrvStat, DispatchDate, DispatchTime, SvcDescription, CustNmbr, Address, "
+ "City, State, Zip, Phone, Equipment, Tracking, SrvType, StatDesc) ";
$.each(result, function () {
insertString = insertString + "Select '{0}' as CallNumber,'{1}' as PoNumber,'{2}' as AdrsCode,'{3}' as SrvStat,'{4}' as DispatchDate,'{5}' as DispatchTime,'{6}' as SvcDescription,'{7}' as CustNmbr,'{8}' as Address,'{9}' as City,'{10}' as State,'{11}' as Zip,'{12}' as Phone,'{13}' as Equipment,'{14}' as Tracking,'{15}' as SrvType,'{16}' as StatDesc Union "
.format(this.CallNumber, this.PoNumber, this.AdrsCode, this.Status, this.DispatchedDate, this.DispatchedTime,
this.Description, this.Customer, this.Address, this.City, this.State, this.Zip, this.Phone, this.Equipment,
this.Tracking, this.SrvType, this.StatDesc);
});
db.transaction(function(tx) {
tx.executeSql(insertString.substring(0, insertString.length - 6), [],
onSqlSuccess, onSqlError);
});
}