1
我有下一個功能。我的PHP腳本返回與元素error
數組與值「ERR」:jQuery Ajax成功變量
var updatePaymentType = function(plan_pt_id, pt_id){
var error = null;
var data = new Object()
data["function"] = "update";
data["payment_type_id"] = pt_id;
data["plan_payment_type_id"] = plan_pt_id;
data["data"] = $("#saveform").serializeArray();
$.ajax({
type: "POST",
url: "<?=ROOT_PATH?>/commission/plan/edit/id/<?=$this->editId?>",
data: data,
dataType: "json",
success : function (data)
{
error = data['error'];
alert(error); // All works. Output ERR
}
});
alert(error); // Not work. Output null
return error;
};
我的函數應該返回一個錯誤。但它返回null
。 非常感謝。
這看起來像問題。爲了進一步解釋,ajax中的「a」代表異步,這意味着你的代碼在繼續執行之前不會等待http請求返回。在這種情況下,您的返回語句將在ajax請求返回一個值之前執行很久,這使得外部函數無法從服務器返回值。通過使用回調,您可以避免這種情況,並將值從服務器返回時傳遞給適當的方法:-) – 2010-10-18 11:38:12
謝謝。它工作得很好。我正在使用handleErrors函數的第二個變體。 – pltvs 2010-10-18 11:57:39
如果需要,您如何訪問另一個函數中的變量錯誤? – pcproff 2012-11-07 19:38:22