通过AJAX调用将返回的JSON分配给localstorage

时间:2014-07-03 09:08:12

标签: javascript jquery ajax asp.net-mvc json

这看起来很简单,但实际上让我感到难过......基本上我试图通过AJAX调用来分配从MVC 4动作返回的有效JSON(允许插入用户)。 JSON正在成功返回但我无法解析客户端上的JSON,因此我可以将变量分配给本地存储。如果有人能告诉我我哪里出错了,我会非常感激,因为我被困在这一整天,谢谢。

JSON

{     “成功”:是的,     “user”:{         “UserId”:7,         “名字”:“鲍勃”,         “电子邮件”:“bob@email.com”,         “职业”:“开发”,         “国家”:“英国”,         “RegistrationNumber”:“B001”,         “UserDate”:“/ Date(1401840000000)/”,         “结果”:null     } }

MVC 4行动

   [HttpPost]
    //[ValidateAntiForgeryToken]
    public ActionResult Create(User user)
    {

        if (ModelState.IsValid)
        {
            repository.InsertUser(user);
            repository.Save();

            if (Request.IsAjaxRequest())
            {

                //success
                return Json(new { Success = true, user }); 

                // no success
                return Json(new { Success = false, Message = "Error" }); 

            }

            return RedirectToAction("Index");
        }
        return View(user);

    }

AJAX     //寄存器   self.create = function(){

if (User.Name() != "" && User.Email() != "" && User.Occupation() != "") {
    $.ajax({
        url: '/User/Create',
        cache: false,
        type: 'POST',
       contentType: 'application/json; charset=utf-8',
        data: ko.toJSON(User),
        success: function (data) {

            if (data.Success) {

                //NOTE the following not working
                var dataToStore = JSON.stringify(data);
    localStorage.setItem("UserId", dataToStore.UserId);

               //NOTE the following alert outputs an undefined message?

                alert(JSON.parse(localStorage.getItem("UserId")))

    //NOTE the following not being assigned either?

                localStorage.setItem("Name", data.Name);
                localStorage.setItem("Email", data.Email);
                localStorage.setItem("Occupation", data.Occupation);
                localStorage.setItem("Country", data.Country);
                localStorage.setItem("RegistrationNumber", data.RegistrationNumber);

                //testing output
                 viewModel.UserId(data.UserId);

                //redirect to questions
              //  window.location = "QnA.html"
            }
            else {
                viewModel.UserId("Error user not created, please try again.");
            }
        },
    }).fail(
        function (xhr, textStatus, err) {
            console.log('fail');
            console.log(xhr.statusText);
            console.log(textStatus);
            console.log(err);
        });

} else {
    alert('Please enter all fields');
}

};

2 个答案:

答案 0 :(得分:1)

首先,当你返回json结果时,将其更新为

 return Json(new { Success = true, user } , JsonRequestBehavior.AllowGet });
 return Json(new { Success = false, Message = "Error" } , JsonRequestBehavior.AllowGet}); 

答案 1 :(得分:1)

访问用户数据时,您必须访问以下内容;

data.user.Name
data.user.Email

并在返回JSON时设置Json请求行为,如下所示;

return Json(new { Success = true, user } , JsonRequestBehavior.AllowGet });

<强> DEMO

谢谢!