这是我的ajax函数和我的ShowResults函数,它们都有效。来自此ajax请求的数据将作为json数组返回:
$.ajax({
url: "some URL",
type: "GET",
dataType: "json",
success: ShowResults,
error: function (jqXHR, textStatus, errorThrown) {
console.log("Not OK")
}
});
function ShowResults (data) {
$.each(data, function (item) {
$("#ResultSelector").append("<option value=>" + data[item] + "</option>");
});
}
});
从此我得到一个动态的项目列表,显示在下拉菜单中(带有id&#39; ResultSelector&#39;)。我需要抓住这个相同的json数据并在另一个函数中使用它。
如何从ajax调用中定义或提取这个json数据,以便我可以在另一个函数中使用它/引用它?
谢谢,
答案 0 :(得分:0)
很简单:
定义javascript variable
并为其分配从ajax response
收到的数据。然后在另一个javascript function
中,您可以使用javascript variable
并获取数据。代码如下:
var ajax_response_data="";
$.ajax({
url: "some URL",
type: "GET",
dataType: "json",
success: ShowResults,
error: function (jqXHR, textStatus, errorThrown) {
console.log("Not OK")
}
});
function ShowResults (data) {
ajax_response_data = data; //assign the ajax response data to the variable
$.each(data, function (item) {
$("#ResultSelector").append("<option value=>" + data[item] + "</option>");
});
}
});
function another_function()
{
//here you can use the data you received from ajax
console.log(ajax_response_data);//call this function and check you console to see the data
}