我无法检查我的代码是否错误或此处是否存在语法错误。我花了更多时间考虑在stackoverflow中提问。
$(document).ready(function () {
AjaxGet = function (url, storeageLocation, mySuccessCallback) {
var result = $.ajax({
type: "GET",
url: "/Regions/GetView",
async: true,
contentType: 'application/json',
dataType: "html",
success: function (viewData) {
alert(viewData);
storeageLocation = viewData;
mySuccessCallback(viewData);
},
error: function (xhr, ajaxOptions, thrownError) {
}
}).responseText;
return result;
};
alert(result);
});
答案 0 :(得分:1)
我认为唯一的问题是,您无法从Ajax调用返回值。
尝试更改return result
,我认为这样可行。您的代码中没有任何问题。
或者只是尝试将ajax请求类型更改为Synchronous。也许就像
async: false;
答案 1 :(得分:1)
Ajax是一种异步技术。因此,您在获得响应之前尝试返回结果。
你可以关闭ajax的async,看起来像这样:
$(document).ready(function () {
AjaxGet = function (url, storeageLocation, mySuccessCallback) {
var result = null;
$.ajax({
type: "GET",
url: "/Regions/GetView",
async: false,
contentType: 'application/json',
dataType: "html",
success: function (viewData, textStatus, jqXHR) {
alert(viewData);
storeageLocation = viewData;
result = textStatus;
mySuccessCallback(viewData);
},
error: function (xhr, textStatus, thrownError) {
result = textStatus;
}
});
return result;
};
alert(result);
});
答案 2 :(得分:1)
$(document).ready(function () {
AjaxGet = function (url, mySuccessCallback) {
var result = $.ajax({
type: "GET",
url: "/Regions/GetView",
async: true,
contentType: 'application/json',
dataType: "html",
success: function (viewData) {
mySuccessCallback(viewData);
},
error: function (xhr, ajaxOptions, thrownError) {
}
}).responseText;
return result;
};
// alert(result); // will throw error: undefined variable 'result', because you used this variable inside function definition 'AjaxGet', not in this context
AjaxGet( '/', function(data) { // call the function after defining it to execute and get the results
alert( data );
} );
});