我有一个foo发出Ajax请求的函数.我怎样才能从中回复foo?
我尝试从success回调中返回值,并将响应分配给函数内部的局部变量并返回该变量,但这些方法都没有实际返回响应.
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});
return result;
}
var result = foo(); // It always ends up being `undefined`.
Run Code Online (Sandbox Code Playgroud) 我正在使用ASP.NET MVC开发一个网站.我正在使用jquery来实现AJAX功能.在动作方法中,我想返回一些错误来表示输入不正确或者无法执行操作.在这种错误情况下,我希望调用jquery ajax错误处理程序,我可以在那里采取适当的操作.我还没有找到办法如何做到这一点.以下是我的行动方法.
在错误的情况下,我应该从Action发送什么才能触发jquery错误处理程序?
public ActionResult AddToFavourites(int entityId, string entityType)
{
if (!Request.IsAjaxRequest())
throw new InvalidOperationException("This action can be called only in async style.");
try
{
RBParams.EntityType typeOfFavourite = (RBParams.EntityType)Enum.Parse(typeof(RBParams.EntityType), entityType);
string status = "";
if (typeOfFavourite == RBParams.EntityType.BusinessEntity)
{
status = MarkFavouriteEntity(entityId);
}
else if (typeOfFavourite == RBParams.EntityType.Review)
{
status = MarkFavouriteReview(entityId);
}
else
{
throw new InvalidOperationException("The type of the entity is not proper");
}
return Content(status);
}
catch (Exception ex)
{
return Content("Error");
}
}
Run Code Online (Sandbox Code Playgroud)