0

嗨,我在通过 ajax jquery 向 web 服务发送数据时遇到问题。

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;
    }
}

谢谢。

4

2 回答 2

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
}  
于 2013-09-26T20:20:28.580 回答
0

我不太确定,但您的 ajax 调用中的参数名称也不应该是“文本”吗?因为这就是你的 web 方法的参数。

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

于 2013-09-26T20:19:30.837 回答