通过 Jquery ajax 将 javascript 对象传递给 webservice

发布于 2024-10-09 13:46:13 字数 1859 浏览 1 评论 0原文

我有一个返回对象的 Web 服务

[WebMethod]
    public List<User> ContractorApprovals()

我也有一个接受对象的 Web 服务

[WebMethod]
    public bool SaveContractor(Object u)

当我通过 Jquery 进行 Web 服务调用时:

function ServiceCall(method, parameters, onSucess, onFailure) {
    var parms = "{" + (($.isArray(parameters)) ? parameters.join(',') : parameters) + "}"; // to json
    $.ajax({
        type: "POST",
        url: "services/"+method,
        data: parms,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            if (typeof onSucess == 'function' || typeof onSucess == 'object')
                onSucess(msg.d);
        },
            error: function(msg, err) {
            $("#dialog-error").dialog('open');}
});

我可以很好地调用第一个。我的 onSucess 函数传递了一个 JavaScript 对象,其结构与我在服务上的 User 对象完全相同。

但是,我现在无法将对象返回到服务器。

我接受对象作为服务器端的参数,所以我无法想象那里存在问题。所以我认为客户端的参数出了问题,但我不确定是什么......

我正在做一些事情,

ServiceCall("AuthorizationManagerWorkManagement.asmx/ContractorApprovals",
      "",
      function(data,args){$("#div").data('user',data[0])},
      null)

然后

ServiceCall("AuthorizationManagerWorkManagement.asmx/SaveContractor",
      JSON.stringify({u: $("#div").data("user")}) //dont work $("#div").data('user'), //These also do not work: "{'u': ' + $("#div").data("user") + '}", NOR JSON.stringify({u: userObject})
      function(data,args){(alert(data)},
      null)

我知道第一个服务调用有效,我可以获取数据。第二个是导致执行“onFailure”方法而不是“OnSuccess”。

有什么想法吗?

更新:

我修改了最后一个要使用的代码块: JSON.stringify({u: $("#div").data("user")})

我现在得到 传递了无效的对象中,应为成员名称。 (1):

但我不知道这意味着什么...谷歌已经发现了很多这样的错误,但没有像我这样的问题...

I have a webservice that returns an object

[WebMethod]
    public List<User> ContractorApprovals()

I also have a webservice that accepcts an object

[WebMethod]
    public bool SaveContractor(Object u)

When I make my webservice calls via Jquery:

function ServiceCall(method, parameters, onSucess, onFailure) {
    var parms = "{" + (($.isArray(parameters)) ? parameters.join(',') : parameters) + "}"; // to json
    $.ajax({
        type: "POST",
        url: "services/"+method,
        data: parms,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            if (typeof onSucess == 'function' || typeof onSucess == 'object')
                onSucess(msg.d);
        },
            error: function(msg, err) {
            $("#dialog-error").dialog('open');}
});

I can call the first one just fine. My onSucess function gets passed a javascript object exactly structured like my User object on the service.

However, I am now having trouble getting the object back to the server.

I'm accepting Object as a parameter on the server side so I can't inagine there is an issue there. So I'm thinking something is wrong with the parms on the client side but i'm not sure what...

I am doing something to the effect

ServiceCall("AuthorizationManagerWorkManagement.asmx/ContractorApprovals",
      "",
      function(data,args){$("#div").data('user',data[0])},
      null)

then

ServiceCall("AuthorizationManagerWorkManagement.asmx/SaveContractor",
      JSON.stringify({u: $("#div").data("user")}) //dont work $("#div").data('user'), //These also do not work: "{'u': ' + $("#div").data("user") + '}", NOR JSON.stringify({u: userObject})
      function(data,args){(alert(data)},
      null)

I know the first service call works, I can get the data. The second one is causing the "onFailure" method to execute rather then "OnSuccess".

Any ideas?

UPDATE:

I chaed my last code block to use : JSON.stringify({u: $("#div").data("user")})

I now get Invalid object passed in, member name expected. (1):

But I have no idea what the means... Google has turned up plenty of that error, but no problem like mine...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

街角迷惘 2024-10-16 13:46:14

好的,我已经发布了代码以及链接,请点击此处

    Default.aspx
        <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs"   Inherits="_Default" %>             
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
    <script type="text/javascript">
        var url = '<%=ResolveUrl("~/WebService.asmx/HelloWorld")%>';
        $(document).ready(function() {
           $('#txtAutoSuggest').keyup(function() {
                var str = $("#txtAutoSuggest").val();
                var a = JSON.stringify({ name: str });
                CallService(a);
                  });

        });

     function CallService(a) {
        $.ajax({
            type: "POST",
           url: url,
           data: a,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
           success: function(data, status) {
                $('#lblResult').text(data.d);
            },
            error: Error
        });
    }
    function Error(request, status, error) {
        $('#lblResult').text("Not Matched");
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtAutoSuggest" runat="server"></asp:TextBox>
        <asp:Label ID="lblResult" Text=" " Width="100%" runat="server" />
    </div>
</form>
</body>
</html>

OR

application.js

 var url = '<%=ResolveUrl("~/WebService.asmx/HelloWorld")%>';
        $(document).ready(function() {
            $('#txtAutoSuggest').keyup(function() {
                var str = $("#txtAutoSuggest").val();
                var a = JSON.stringify({ name: str });
                CallService(a);
            });

        });

    function CallService(a) {
        $.ajax({
            type: "POST",
            url: url,
            data: a,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data, status) {
                $('#lblResult').text(data.d);
            },
            error: Error
        });
    }
    function Error(request, status, error) {
        $('#lblResult').text("Not Matched");
    }




<%@ WebService Language="C#" Class="WebService" %>
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;




 [WebService(Namespace = "http://tempuri.org/")]
 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

// 允许使用 ASP.NET AJAX 或 JQuery 从脚本调用此 Web 服务。

[System.Web.Script.Services.ScriptService]
 public class WebService  : System.Web.Services.WebService {

    [WebMethod]
    public string HelloWorld(string name)
    {
        Utility ut = new Utility();  // some class where you will have your database connection
        ArrayList suggestedProblemName = ut.getItems(name);  // some method of the class
        return ""+suggestedProblemName[0];
    } 
}

Ok I have posted the code as well as a link over Click here!

    Default.aspx
        <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs"   Inherits="_Default" %>             
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
    <script type="text/javascript">
        var url = '<%=ResolveUrl("~/WebService.asmx/HelloWorld")%>';
        $(document).ready(function() {
           $('#txtAutoSuggest').keyup(function() {
                var str = $("#txtAutoSuggest").val();
                var a = JSON.stringify({ name: str });
                CallService(a);
                  });

        });

     function CallService(a) {
        $.ajax({
            type: "POST",
           url: url,
           data: a,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
           success: function(data, status) {
                $('#lblResult').text(data.d);
            },
            error: Error
        });
    }
    function Error(request, status, error) {
        $('#lblResult').text("Not Matched");
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtAutoSuggest" runat="server"></asp:TextBox>
        <asp:Label ID="lblResult" Text=" " Width="100%" runat="server" />
    </div>
</form>
</body>
</html>

OR

application.js

 var url = '<%=ResolveUrl("~/WebService.asmx/HelloWorld")%>';
        $(document).ready(function() {
            $('#txtAutoSuggest').keyup(function() {
                var str = $("#txtAutoSuggest").val();
                var a = JSON.stringify({ name: str });
                CallService(a);
            });

        });

    function CallService(a) {
        $.ajax({
            type: "POST",
            url: url,
            data: a,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data, status) {
                $('#lblResult').text(data.d);
            },
            error: Error
        });
    }
    function Error(request, status, error) {
        $('#lblResult').text("Not Matched");
    }




<%@ WebService Language="C#" Class="WebService" %>
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;




 [WebService(Namespace = "http://tempuri.org/")]
 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

// To allow this Web Service to be called from script, using ASP.NET AJAX or JQuery.

[System.Web.Script.Services.ScriptService]
 public class WebService  : System.Web.Services.WebService {

    [WebMethod]
    public string HelloWorld(string name)
    {
        Utility ut = new Utility();  // some class where you will have your database connection
        ArrayList suggestedProblemName = ut.getItems(name);  // some method of the class
        return ""+suggestedProblemName[0];
    } 
}
ぽ尐不点ル 2024-10-16 13:46:13
 ServiceCall("AuthorizationManagerWorkManagement.asmx/SaveContractor",
            "{u: " + JSON.stringify($("#div").data("user")) + "}",
            function(data, args) { alert(data); },
            FailedServiceCall);
 ServiceCall("AuthorizationManagerWorkManagement.asmx/SaveContractor",
            "{u: " + JSON.stringify($("#div").data("user")) + "}",
            function(data, args) { alert(data); },
            FailedServiceCall);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文