代码之家  ›  专栏  ›  技术社区  ›  Alexander

如何使用异步调用方法并显示数据?当我试着

  •  0
  • Alexander  · 技术社区  · 7 年前

    我有一个方法,在那里我读一个人的一些细节。有点像大师级的细节。 当我用ajax参数调用方法时async:true,它失败了。它什么也不做,不显示popover,也不在控制台中抛出任何异常。 C级#

    public async Task<ActionResult> PersonDetails(int id)
        {
            var model =  await _context.Person.Where(e => e.Person == id && e.Age > 5).ToListAsync();
            return View(model);
        }
    

    ajax调用:

    $.ajax({
                url: "/Home/PersonDetails/" + id,
                method: "post",
                async: true,
    
                //data: { id: id },
                success: function (data) {
                    set_data = data;
                },
                error: function (jqXHR, textStatus, errorThrown) {
    
                    console.log(jqXHR.statusText + textStatus + errorThrown);
                }
            });
    

    当控制器中没有async、Task和await,并且async设置为false时,它就工作了。同样,如果我在控制器上保留async Task和await,并将ajax async设置为false,它也工作了。 如何解决这个问题?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Will    7 年前
    1. $.ajax() 调用本质上是异步的,默认为true,因此不需要添加 async: true

    2. 使用 data: { id: id } + id url:

    3. 替换 async Task<ActionResult> JsonResult using System.Web.Mvc )

    4. 添加 [HttpPost] public JsonResult PersonDetails(int id) { ... }

    5. 使用 var model = _context.Person.Where(e => e.Person == id && e.Age > 5).ToList();

    6. 返回 return Json(model);

    7. 完成!你可以 console.log(data); 在$.ajax.success函数中查看返回数据

        2
  •  0
  •   Alexander    7 年前