无法通过jquery将数据发送到webservice

时间:2013-09-26 20:14:39

标签: jquery asp.net web-services

  

您好,我无法通过ajax向webservice发送数据   jquery的。

     

onclient方法触发但不会转到服务

这是我的aspx页面代码:

        <script src="Scripts/jquery-1.7.1.js"></script>
        <script type="text/javascript">
            function Start() {
                debugger;
                $.ajax({

                    type: "POST",
                    url: "WebService.asmx/Start",
                    data: '{speakstr: "' + $("#lbl").html() + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        // alert(msg.d);
                    }
                });
                return false;
            }
        </script>
        <title></title>
    </head>

    <body>

        <form id="form1" runat="server"> 
            <div>
                <asp:Label ID="lbl" Text="text" runat="server" />
                <asp:Button ID="Btn" Text="listen" runat="server" OnClientClick="Start()" />
            </div>
        </form>

这是我简单的webservice.asmx页面:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{

    public WebService()
    {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public static void Start(string text)
    {
        string txt = text;
    }
}
  

感谢。

2 个答案:

答案 0 :(得分:1)

试试这个: 更改代码js代码:

   function Start() {
                $.ajax({
                    type: "POST",
                    url: "WebService.asmx/Start",
                    data: JSON.stringify({"text" : $("#lbl").html()}),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        alert(msg.d);
                    }
                });
            }

并在asmx中更改方法:

[WebMethod]
public static string Start(string text)
{
    string txt = text;
    return txt; // just for test
}  

答案 1 :(得分:0)

我不太确定,但不应该在你的ajax调用中输入你的参数名称 是“文字”吗?因为那是你web方法的参数。

另外,我不太确定,但不应该在[Webmethod]之后有括号吗?