【问题标题】:I want to send a class array with ajax but, when I make a request, the request does not reach the backend side我想用ajax发送一个类数组,但是当我发出请求时,请求没有到达后端
【发布时间】:2019-09-14 08:18:07
【问题描述】:

我想用 ajax 发送一个类数组,但是当我发出 ajax 请求时,请求没有到达后端。当我发送一个字符串数组请求时。它工作得很好。但是如果 Array 包含一个类,就好像没有请求一样。

这是我的 javascript 类:

var image_base64_code = [];

class images_base64 {
        constructor(id, base64, name) {
            this.id = id;
            this.base64 = base64;
            this.name = name;
        }
    }
//***************************************
//  there are some codes here. For information.
//***************************************

image_base64_code.push(new images_base64(preview_intex, image_base64,name));

这是我的 ajax 请求:

$('#Ajax').click(function () {

            var ImageJsonText = JSON.stringify({ image_base64_code: image_base64_code});

            $.ajax({
                url: 'main.aspx/ImageSave',
                dataType: 'json',
                type: 'POST',
                data: ImageJsonText,
                traditional: true,
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    alert(data.d);
                }
            });
        });
    });

还有我的后端功能:

[WebMethod]
public static bool ImageSave(RequestImage[] image_base64_code)
{


     return 1;
 }

public class RequestImage{
   public string id;
   public string base64;
   public string name;
}

【问题讨论】:

  • traditional: true, 是干什么用的?而且,您的 ajax 调用有太多 });

标签: javascript c# jquery asp.net ajax


【解决方案1】:

使用对象

var image_base64_code = {};              // object.
image_base64_code["images"] = [];
image_base64_code["images"].push( ... ); // add new here. 

var ImageJsonText = JSON.stringify(image_base64_code);

JSON.stringify 将对象转换为字符串,因此将public static bool ImageSave(RequestImage[] image_base64_code) 更改为接受字符串。

public static bool ImageSave(string image_base64_code)
{
    return 1;
}

在此方法中,您可以使用内置的 javascript deserializer 或 JSON.NET (Newtonsoft) 等库将字符串转换为 RequestImage 对象(反序列化)。


另见:JSON.stringify doesn't work with normal Javascript array

【讨论】:

  • 谢谢,但是请求无效。没有去功能。
猜你喜欢
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
  • 2020-04-05
  • 2013-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多