Javascript在函数调用时终止

时间:2011-04-24 15:31:21

标签: javascript jquery asp.net jquery-ui

我正在尝试连续两天从客户端进行服务器方法调用。浏览了许多博客和帖子。我是jquery的新手,因此一直依赖于在线演示。我现在面临的问题是我的jquery将在调用时启动并在其中使用的函数调用终止。我可以在这里得到一些帮助吗?样本代码随附于此。您也可以在以下链接http://aspdotnetcode.source-of-humor.com/Articles/JQuery/JqueryAjaxRequestForCallingASPNetServerSideFunction.aspx中找到此代码。任何帮助,将不胜感激。

aspx页面

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="JqueryAjaxRequestSample.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="jquery-1.4.2.min.js" type="text/javascript"></script>

<script type="text/javascript" language="javascript">

  function InitiateJqueryAjaxRequestCall() {

    var reqParameter1 = $('#<%= txtParameter1.ClientID %>')[0].value;
    var reqParameter2 = $('#<%= txtParameter2.ClientID %>')[0].value;

    var requestParameters = '{' +
                            'reqParameter1:"' + reqParameter1 + '", ' +
                            'reqParameter2:"' + reqParameter2 + '"' +
                            '}';

    // Configure AJAX call to server                        
    $.ajax({
      type: "POST",
      url: "JqueryAjaxRequestSample.aspx/GetSum",
      data: requestParameters,
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: DisplayResponse,//Event that'll be fired on Success
      error: DisplayError //Event that'll be fired on Error
    });
  }
  function DisplayResponse(serverResponse) {            
    alert('Server Response: Sum of numbers is = '+serverResponse.d);
  }
  function DisplayError(serverResponse) {
    alert("Some Error Occured");
  }

</script>

</head>
<body>
   <form id="form1" runat="server">
    <asp:TextBox ID="txtParameter1" runat="server"></asp:TextBox>
    <asp:TextBox ID="txtParameter2" runat="server"></asp:TextBox>
    <input id="btnSendJqueryCall" onclick="InitiateJqueryAjaxRequestCall();" type="button"
        value="Invoke Page Method using JQuery" />
</form>

</body>
</html>

代码隐藏

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static int GetSum(int reqParameter1, int reqParameter2)
    {
        return reqParameter1 + reqParameter2;
    }

}

1 个答案:

答案 0 :(得分:0)

如果你发送这样的参数,它可以工作:

var requestParameters = '{ reqParameter1:1, reqParameter2:2 }';

因此,您没有正确创建参数。