我正在尝试读取包含ajax调用的函数p_info
返回的getproductInfo
数组,但是我得到了未定义的值。我正在使用回调函数来实现这一点,但仍然无法正常工作。我哪里错了?
$(document).ready(function() {
function successCallback(data)
{
var name = data.name;
var image = data.image;
var link = data.link;
var product_info = [name, image, link];
console.log(product_info); // Correct: shows my product_info array
return product_info;
}
function getProductInfo(prodId, successCallback) {
$.ajax({
type: "POST",
url: "getProductInfo.php",
data: "id=" + prodId,
dataType: "json",
success: function(data) {
var p_info = successCallback(data);
console.log(p_info); // Correct: shows my product_info array
return p_info;
},
error: function()
{
alert("Error getProductInfo()...");
}
});
return p_info; // Wrong: shows "undefined" value
}
var p_info = getProductInfo(12, successCallback);
console.log(p_info); // Wrong: shows an empty value
});
答案 0 :(得分:0)
代码应该说明一切。但基本上,你不能在函数内返回一个高级函数。您必须设置一个变量,用于在提交ajax后返回。
//This makes the p_info global scope. So entire DOM (all functions) can use it.
var p_info = '';
//same as you did before
function successCallback(data) {
var name = data.name;
var image = data.image;
var link = data.link;
var product_info = [name, image, link];
return product_info;
}
//This takes prodID and returns the data.
function getProductInfo(prodId) {
//sets up the link with the data allready in it.
var link = 'getProductInfo.php?id=' + prodId;
//creates a temp variable above the scope of the ajax
var temp = '';
//uses shorthand ajax call
$.post(link, function (data) {
//sets the temp variable to the data
temp = successCallback(data);
});
//returns the data outside the scope of the .post
return temp;
}
//calls on initiates.
var p_info = getProductInfo(12);
console.log(p_info);