写了个函数,输入三个参数,前两个参数传给url, 通过get请求,获取发票信息对象,第三个参数判断要获取的信息,从然后返回对应的值。
同事点拨,这样写效率低,直接返回对象,用的时候现取,不需要在函数中返回值。果然沟通使人进步。 改进后的代码:
function getInvocieInfo(user_id, taskid) {
var invoiceObj = {};
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://180ly66419.iok.la:5000/api/detect_in?1=1&user_id=' + user_id + '&task_id=' + taskid,
async: false,
timeout: 5,
data: {
q: "select * from json where url=\"http://www.w3dev.cn/json.asp\"",
format: "json"
},
success: function (response) {
responseData = JSON.stringify(response);
invoiceObj = eval('(' + responseData + ')');
},
error: function () {
alert('服务器异常,获取发票信息失败!');
}
});
return invoiceObj
}
使用的时候调用:
var inoviceObj = getInvocieInfo(user_id, taskList[i]);
invoiceInfo["invoiceTextID"] = inoviceObj.data["invoice_code"];
invoiceInfo["invoiceTextNum"] = inoviceObj.data["invoice_num"];
修改前
function getInvocieInfo(user_id, taskid, textInvocetype) {
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://180ly66419.iok.la:5000/api/detect_in?1=1&user_id=' + user_id + '&task_id=' + taskid,
async: false,
timeout: 5,
data: {
q: "select * from json where url=\"http://www.w3dev.cn/json.asp\"",
format: "json"
},
success: function (response) {
responseData = JSON.stringify(response);
var invoiceObj = eval('(' + responseData + ')');
invoiceID = invoiceObj.data['invoice_code'];
invoiceNo = invoiceObj.data['invoice_num'];
},
error: function () {
alert('服务器异常,获取发票信息失败!');
}
});
if (textInvocetype == "textInvoiceNum") {
return invoiceNo;
}
else if (textInvocetype == "textInvoiceID") {
return invoiceID;
}
}