繁体   English   中英

如何使用jquery将json数据发送到asmx(来自aspx)?

[英]how to send json data to asmx (from aspx) using jquery?

我在aspx 3.5中构建了联系表单,我使用jQuery将其发送到Web服务(asmx)。

Web服务需要返回成功或错误代码。 问题是在web方法中我只得到单个值而不是数组。 我是ajax的新手,我尝试了很多解决方案,但没有任何结果。 如果你只能解释我做什么的原则也很好。

这是客户端:

$(document).ready(function() 
{
    $("#submit").click(function(event)
    {
        $.ajax
        ({
            type: "POST",
            url: "RVContactFormMailer.asmx/HelloToYou",                
            data: "{'name': '" + $('#name').val() + "', 'company':'" + $('#company').val() + "', 'phone':'" + $('#phone').val() + "', 'email':'" + $('#email').val() + "', 'questions':'" + $('#questions').val() + "'}" ,                 
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
            AjaxSucceeded(msg);
         }, error: AjaxFailed
        });
   });

在firebug中它正确发送:

{'name': 'jhon', 'company':'example', 'phone':'123', 'email':'jhon@jhon.com', 'questions':'hello'}

asmx代码是(请忽略名称,其示例:

  [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService] // To allow this Web Service to be called from script, using ASP.NET AJAX or JQuery.
    [ToolboxItem(false)]
    public class RVContactFormMailer : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]  
        public string HelloToYou(string name)
        {
            return "Hello " + name;
        }
    }

当我调试时,我看到输入参数“name”只包含一个字符串 - 我不知道如何获取我发送给服务的完整json字符串并包含所有表单数据 - 我想将它转换为字符串数组或类似的东西,并处理它。 我怎样才能做到这一点?

问题不在客户端 - 它在服务器端 - 问题是我向Web服务发送了少量参数,但函数只有一个:

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string HelloToYou(string name)

而正确的应该是:

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string HelloToYou(string name, string company, string phone, string email, string questions)

无论如何, 谢谢你的帮助!

你试过看request.form集合吗? 由于您正在发布请求并将params作为数据传递给请求,因此它将在Request.Form中可用。

暂无
暂无

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

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