简体   繁体   中英

Can not send data from c#(controller) to javascript

I have this code on my JavaScript file:

temp="string";
var myJson = JSON.stringify(temp);
    $.ajax(
        {
            url: '/MemoryGame/updateStatus',
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: myJson,
            success: function (response) {
                alert("success");
                if (response == 'Okay') {
                    checkStatus(temp.myID);
                }
               else {
                    ConnectionChanged();
                }
            },
            error: function (errorThrown) {
                console.log(errorThrown);
                ConnectionChanged();
            }
        });

And this controller:

[HttpPost]
        public string updateStatus(string updatedJson)
        {

            var Player = JsonConvert.DeserializeObject<GameDataClass>(updatedJson);
            var Opponent = JsonConvert.DeserializeObject<GameDataClass>(System.IO.File.ReadAllText(System.IO.Path.Combine(_env.WebRootPath, Player.OpponentID + ".json"))); 
... }

I tried to change $.ajax to $.post method, also changed

public string updateStatus

to

public JsonResult updatedStatus

But neither of this didn't work. myJson on javascript contain data but when it reaches controller updatedJson is empty. I've never had this kind of experience so I'm using this code from another project and it works very well there. So can somebody suggest me what I'm doing wrong?

$.ajax is a fonction from the jQuery library, does your project include it?

You can also check the Javascript console of your browser to see if it contains errors. On Firefox and Chrome you can access it by pressing F12.

    temp="string";
    // (0)
    var myJson = JSON.stringify(temp);
    $.ajax(
        {
            url: '/MemoryGame/updateStatus?updatedJson=' + temp, // (1)
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '',   // (2)
            success: function (response) {
                alert("success");
                if (response == 'Okay') {
                    checkStatus(response.myID);
                }
               else {
                    ConnectionChanged();
                }
            },
            error: function (errorThrown) {
                ConnectionChanged();
            }
        });

Or if this does not have to be passed as a parameter, then do the following: (0) var formData = new FormData(); formData.append('updatedJson', temp); (1) url: '/MemoryGame/updateStatus', (2) data: formData,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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