简体   繁体   English

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

[英]Assign returned JSON to localstorage via AJAX call

This seems so simple but has really stumped me..basically I am trying to assign valid JSON being returned from an MVC 4 action (allows the inserting of a user) via an AJAX call. 这似乎很简单,但确实让我感到难过。基本上,我试图分配一个通过AJAX调用从MVC 4操作(允许插入用户)返回的有效JSON。 The JSON is being returned successfully but I cannot parse the JSON on the client side so that I can assign the variables to local storage. JSON已成功返回,但是我无法在客户端解析JSON,因此可以将变量分配给本地存储。 If someone could please show me where I am going wrong I would be very grateful as I have been stuck on this for one whole day, thanks. 如果有人可以告诉我我哪里出了问题,我将不胜感激,因为我整整一天都被困在这里,谢谢。

JSON JSON

{ "Success": true, "user": { "UserId": 7, "Name": "Bob", "Email": "bob@email.com", "Occupation": "Dev", "Country": "UK", "RegistrationNumber": "B001", "UserDate": "/Date(1401840000000)/", "Results": null } } {“成功”:true,“用户”:{“ UserId”:7,“名称”:“ Bob”,“电子邮件”:“ bob@email.com”,“职业”:“ Dev”,“国家”: “ UK”,“ RegistrationNumber”:“ B001”,“ UserDate”:“ / Date(1401840000000)/”,“ Results”:null}}

MVC 4 Action 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 //Register self.create = function () { 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');
}

}; };

Firstly when ur returning json result update it as follow 首先,当您返回json结果时,如下更新

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

When accessing user data you have to access like follows; 访问用户数据时,您必须按如下方式访问;

data.user.Name
data.user.Email

And set the Json request behavior when you return JSON as follows; 并按如下所示设置返回JSON时的Json请求行为;

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

DEMO DEMO

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM