Return Json with Xmlhttprequest

Asked

Viewed 82 times

0

How to popular a table with a JSON using XMLHttpResquest POST?

Jquery

  var xhr = new XMLHttpRequest();
        xhr.open("POST", "/EnvioEmail/PlanilhaPaciente", { area: "Sistema" }, true);
        xhr.addEventListener("load", function (Lista) {
           //table que recebera o resultado do json
            $('#conteudo-lista-envio-manual').html(Lista);
        }, false);
        xhr.addEventListener("error", function (Lista) {
            msgErro;
        }, false);
        xhr.send(formdata);

C#

[HttpPost]
    public JsonResult PlanilhaPaciente(HttpPostedFileBase planilha)
    {
        if (Request.Files["planilha"].ContentLength > 0)
        {
            var pacientes = new ContatosEmailModelView();
            var msgerro = "";
            if (ValidaPlanilha(planilha, out pacientes, out msgerro))
                return Json(new { erro = false, Lista = pacientes.ListaContatos }, JsonRequestBehavior.AllowGet);
            else
                return Json(new { erro = true, msgErro = msgerro }, JsonRequestBehavior.AllowGet);

        }
        return Json(new { erro = true, msgErro = "Não existe registro no arquivo" }, JsonRequestBehavior.AllowGet);

    }
  • Your question is very simple, if you can detail more, as for example, post the javascript object that goes to this request. And if there is any object on the server that represents your view object.

1 answer

0


I solved it. Create generating functionBody with each to generate tr and td tags in table passing value

this.carregaPlanilha = function () {
        var vPlanilha = $('#FileUpload')[0].files[0];

        var formdata = new FormData();
        formdata.append('planilha', vPlanilha);

        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/EnvioEmail/PlanilhaPaciente", { area: "Sistema" }, true);
        xhr.addEventListener("load", function (Lista) {
            var pacientes = Lista.currentTarget.response;
            $("#conteudo-lista-envio-manual tbody").append(me.geraBody(JSON.parse(pacientes).Lista));
        }, false);
        xhr.addEventListener("error", function (Lista) {
            msgErro;
        }, false);
        xhr.send(formdata);
    };
  • only the function needed to be included geraBody() in his reply ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.