1

我不知道发生了什么,但我的 Ajax 查询之一停止工作。我有 2 个视图,在第一个用户中选择按钮的颜色

function choose()

    {
        var a = document.getElementById("button1").style.backgroundColor.toString();
        var b = document.getElementById("button2").style.backgroundColor.toString();
        var c = document.getElementById("button3").style.backgroundColor.toString();
        var d = document.getElementById("button4").style.backgroundColor.toString();
        if (a && b && c && d != "") {
            $.ajax({
                url: '@Url.Action("SetCode", "Home")',
                type: 'POST',
                data: { a, b, c, d },
                
}).done(function(res) {
     window.location.href = res.newUrl;
}).fail(function(xhr, a, error) {
      console.log(error);
});

然后在控制器中,颜色保存在单例类中

Kod o1 = Kod.makeObject();
        [HttpPost]
        public JsonResult SetCode(string a, string b, string c, string d)
        {
         
            o1.FirstColor = a;
            o1.SecondColor = b;
            o1.ThirdColor = c;
            o1.FourthColor = d;

            return Json(new { newUrl = Url.Action("Game", "Home") });
        }; 

之后有一个重定向到控制器“游戏”中返回视图的方法。在此视图中,下一个用户选择颜色并检查它们是否正确

  public IActionResult Game()
        {
          return View();
        }
 function checkcode() {
        var a = document.getElementById("button1").style.backgroundColor.toString();
        var b = document.getElementById("button2").style.backgroundColor.toString();
        var c = document.getElementById("button3").style.backgroundColor.toString();
        var d = document.getElementById("button4").style.backgroundColor.toString();
        if (a && b && c && d != "") {
              $.ajax({
                url: '@Url.Action("Check", "Home")',
                dataType: "text",
                type: 'POST',
                data: {a , b, c, d },
                success: function (data) {
                    if (data == true) {
                        alert("OK")
                    } else { alert("Error") }
                }
            });

在控制器方法中,我总是在可变量 e、f、g、h 中收到空值。怎么了?

[HttpPost]
public bool Check(string e, string f, string g, string h)
        {
       
            if (o1.FirstColor == e && o1.SecondColor == f && o1.ThirdColor == g && o1.FourthColor == h)
            {
              return true;
            }
            else { return false; }
        }

4

1 回答 1

0

您需要更改data: {a , b, c, d },data: { e:a, f:b, g:c, h:d },.

如果使用data: {a , b, c, d },request会传递参数name是哪个a,b,c,d,所以你需要把它们的名字改成e,f,g,h.

使用data: {a , b, c, d }时,请求数据为: 在此处输入图像描述

使用data: { e:a, f:b, g:c, h:d },时,请求数据为: 在此处输入图像描述

更新:

您需要更改data == truedata == "true",当您将 true 传递给 ajax 时,数据将是"true". 在此处输入图像描述

于 2021-09-27T03:01:15.037 回答