【问题标题】:Jquery ASMX Web Service call - send / receive complex typesJquery ASMX Web Service 调用 - 发送/接收复杂类型
【发布时间】:2010-11-01 21:09:15
【问题描述】:

不确定是一天中的某个时间、缺乏咖啡还是昨晚过度放纵糖。除此之外,我正试图让这个工作。我不想更改/修改/添加新的 Web 服务方法。

我有一个 asmx 网络服务:

public UserLogin Login(UserLogin p_objUserLogin)
{
}

我需要连接一个 JQuery ajax 调用。 UserLogin 对象并不复杂:

public class UserLogin
{
    public UserLogin();

    public string Privileges { get; set; }
    public string ClientCodeID { get; set; }
    public UserDetails User { get; set; }
    public string UserLoginMessage { get; set; }
    public bool Valid { get; set; }
}

UserDetails 对象非常大,包含更多数据。 (希望我不需要构建整个对象树来让它工作)。

public class UserDetails
{
    public string CellPhone { get; set; }
    public string Email { get; set; }
    public string EncryptedPassword { get; set; }
    public string FirstName { get; set; }
    public string FullName { get; }
    public string Initials { get; set;
    public bool InService { get; set; }
    public string LastName { get; set; }
    public string Password { get; set; }
    public byte[] Signature { get; set; }
    public string SimCard { get; set; }      
    public int UserID { get; set; }
    public string UserName { get; set; }
    public SecurityRole UserSecurityRole { get; set; }
    public Workgroup UserWorkgroup { get; set; }
}

我正在玩的脚本:

function CallService() {
    var p_objUserLogin = {};
    p_objUserLogin['ClientCodeID'] = "Test";
    var DTO = { 'p_objUserLogin': p_objUserLogin };
    $.ajax({
        type: "POST",
        url: "UtilityServices2006.asmx/Login",
        data: JSON.stringify(DTO),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        processData: true,
        success: function (msg) {
            alert(msg);
        },
        error: function (req, status, error) {
            alert(req + ", " + status + ", " + error);
        },
        complete: function (req, status) {
            alert(req + ", " + status);
        }
    });

}

任何帮助都会非常棒。

【问题讨论】:

  • WebMethod 调用是否完全失败。如果不是,您在 Login 方法中获得的对象是什么样的?
  • 服务器上的登录方法?通常由 ClientID、UserName、EncryptedPassword 填充。我的网络服务根本没有受到打击。也不会生成肥皂日志。

标签: javascript .net jquery ajax asmx


【解决方案1】:

确保您的 Web 服务类和方法经过修饰以处理传入的 ajax/json 请求:

[ScriptService]
public class MyService: WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public UserLogin Login(UserLogin p_objUserLogin)
    {
    }
}

我不熟悉您用于配置有效负载对象的表示法 (p_objUserLogin['ClientCodeID'] = "Test";)。我通常使用稍微不同的符号:

p_objUserLogin.ClientCodeID = 'Test';

但是,这可能是一个红鲱鱼 - 我不是 JS 对象专家,所以你的符号可能是完全有效的。

最后,我不确定 JS 是否会自动将您的对象转换为 JSON(var DTO = { 'p_objUserLogin': p_objUserLogin };)。我使用json2 library 将 JS 对象显式序列化为 JSON:

var DTO = { 'p_objUserLogin': JSON.stringify(p_objUserLogin) };

希望这可以帮助您解决问题。

【讨论】:

  • 感谢您的回复。我确实使用 JSON.Stringify,但会尝试像你说的那样将它移动到 DTO var 中。
猜你喜欢
  • 2012-12-09
  • 1970-01-01
  • 2014-05-20
  • 2023-03-27
  • 2018-01-11
  • 2016-03-01
  • 2020-02-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多