调用WebServices Jquery

时间:2011-03-15 18:29:50

标签: c# jquery

我有一个简单的ajax请求,我试图调用我创建的Web服务。 Web服务代码永远不会被执行。我从网上得到了这个代码示例,我想也许我在jquery中调用url错误我不知道吗?

这是jquery

<script type="text/javascript">
    $(document).ready(function() { 

    alert("Hi");
        $("#btnTitleQuery").bind("click", function() {
            $("#query_results").empty();
            $("#query_results").append('<table id="ResultsTable" class="BooksTable"><tr><th>BookNum</th><th>Title</th><th>Author</th></tr>');
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "BookServices.asmx/GetBooksByTitle",
                data: '{ strTitle: "' + $("#txtTitle").val() + '" }',
                dataType: "json",
                success: function(msg) {
                    var c = eval(msg.d);
                    for (var i in c) {
                        $("#ResultsTable tr:last").after("<tr><td>" + c[i][0] + "</td><td>" + c[i][1] + "</td><td>" + c[i][2] + "</td></tr>");
                    }
                }
            });
        })
        $("#btnAuthorQuery").bind("click", function() {
            $("#query_results").empty();
            $("#query_results").append('<table id="ResultsTable" class="BooksTable"><tr><th>BookNum</th><th>Title</th><th>Author</th></tr>');
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "BookServices.asmx/GetBooksByAuthor",
                data: '{ strAuthor: "' + $("#txtAuthor").val() + '" }',
                dataType: "json",
                success: function(msg) {
                    var c = eval(msg.d);
                    for (var i in c) {
                        $("#ResultsTable tr:last").after("<tr><td>" + c[i][0] + "</td><td>" + c[i][1] + "</td><td>" + c[i][2] + "</td></tr>");
                    }
                }
            });
        })
    }); 
</script>

Web服务位于我的根目录中。

using System;

 using System.Web;

 using System.Collections;

 using System.Web.Services;

using System.Web.Services.Protocols;

 using System.Data;

  using System.Data.Odbc;

   using System.Web.Script.Serialization;

 using System.Web.Script.Services;

namespace TryWillJSON
{

 [WebService(Description = "Web services to query the book database.", Namespace = "http://www.williamsportwebdeveloper.com/")]

  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

   [ScriptService]

 public class BookServices : System.Web.Services.WebService {



       public BookServices () {



        //Uncomment the following line if using designed components 

         //InitializeComponent(); 

     }



     [WebMethod(Description = "Gets the books matching part of a title.")]

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

     public string GetBooksByTitle(string strTitle) {

        OdbcConnection objConnection = new OdbcConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Books"].ConnectionString);

         OdbcCommand objCommand = new OdbcCommand("SELECT * FROM reading WHERE Title LIKE '%" + strTitle + "%' ORDER BY BookNum;", objConnection);

         DataSet objDataSet = new DataSet();

         OdbcDataAdapter objDataAdapter = new OdbcDataAdapter(objCommand);

         objDataAdapter.Fill(objDataSet, "reading");

           objConnection.Close();



         // Create a multidimensional jagged array

        string[][] JaggedArray = new string[objDataSet.Tables[0].Rows.Count][];

        int i = 0;

         foreach (DataRow rs in objDataSet.Tables[0].Rows)

        {

            JaggedArray[i] = new string[] { rs["BookNum"].ToString(), rs["Title"].ToString(), rs["Author"].ToString() };

             i = i + 1;

          }



        // Return JSON data

         JavaScriptSerializer js = new JavaScriptSerializer();

      string strJSON = js.Serialize(JaggedArray);

       return strJSON;

      }



     [WebMethod(Description = "Gets the books matching part of an author's name.")]

   [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

    public string GetBooksByAuthor(string strAuthor)

       {

         OdbcConnection objConnection = new OdbcConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Books"].ConnectionString);

         OdbcCommand objCommand = new OdbcCommand("SELECT * FROM reading WHERE Author LIKE '%" + strAuthor + "%' ORDER BY BookNum;", objConnection);

         DataSet objDataSet = new DataSet();

        OdbcDataAdapter objDataAdapter = new OdbcDataAdapter(objCommand);

        objDataAdapter.Fill(objDataSet, "reading");

        objConnection.Close();



          // Create a multidimensional jagged array

         string[][] JaggedArray = new string[objDataSet.Tables[0].Rows.Count][];

        int i = 0;

        foreach (DataRow rs in objDataSet.Tables[0].Rows)

      {
             JaggedArray[i] = new string[] { rs["BookNum"].ToString(), rs["Title"].ToString(), rs["Author"].ToString() };

             i = i + 1;

        }



          // Return JSON data

        JavaScriptSerializer js = new JavaScriptSerializer();

         string strJSON = js.Serialize(JaggedArray);

         return strJSON;

     }



   }
}

我可以看到警报命中,但是在我查看jquery函数的“msg”参数中的什么时,firebug告诉我这个“ReferenceError:msg未定义”

以下是我获取代码的地方: williamsportwebdeveloper.com/cgi/wp/?p=494

如果有人有时间,你可以看看你是否可以在visual studio中正确设置

这是一个小提琴,我设置了它的价值 http://jsfiddle.net/npl77/U33XS/

4 个答案:

答案 0 :(得分:2)

您的参数在属性名称周围没有正确的单个刻度标记 重写它们看起来像这样:

data: "{ 'strAuthor': '" + $("#txtAuthor").val() + "' }",

data: "{ 'strTitle': '" + $("#txtTitle").val() + "' }",

因此,在服务器端检查时,您的参数不匹配。因此,您的代码永远不会被执行。这是我发现的第一个错误......可能会有更多,

检查然后我们会看到。

此外,您可以在javascript中本地使用JSON,这将使这个繁琐且错误的字符串构建过程脱手。你只需要在这里获得一个小JSON库的副本并将其添加到你的项目中(它只是一个javascript文件btw)。

http://sourceforge.net/projects/json-lib/files/

这是一个例子

 //using native JSON
    var per = { FirstName: $('#fName').val(),
                LastName : $('#lName').val(),
                Address : $('#address').val(),
                City : $('#city').val(),
                State : $('#state').val(),
                ZipCode : $('#zip').val()
              };

   $.ajax(
   {
       type: "POST",
       url: "Default.aspx/GetPersonObj",
       data: JSON.stringify(per),  //<---- right here the magic happens
       contentType: "application/json; charset=uft-8",
       dataType: "json",
       success: function (rsp) { SetPerson(rsp); },
       error: function (rsp)
       {
           alert(rsp.responseText); //<--- this is always good to add, that way you can get some feedback from the ajax call about what the hell went wrong.
       }
   });

答案 1 :(得分:0)

进行AJAX调用的文件的位置是什么?也许尝试修改你的JQuery URL:

url: "/BookServices.asmx/GetBooksByTitle",

答案 2 :(得分:0)

尝试使用Firefox / Firebug / Console或IE + Fiddler查看$ .ajax()调用发生的情况。您还可以向该$ .ajax()调用添加错误处理程序以捕获错误事件并吐出一些信息。

是否有任何要求?

你说“Web服务代码永远不会被执行。”所以我猜你有一个调试器附加到VS.NET网站,但是由于断点没有被击中,你需要确定发生了什么客户端第一方。

答案 3 :(得分:0)

尚未提及的一些事情。

1)那些按钮是<input type="submit" />(默认情况下asp:Button呈现的是什么)?如果是这样,您需要阻止其默认操作,以便在您的AJAX请求开始的同时不重新加载页面。

如果按钮正在触发提交,您应该阻止在事件处理程序顶部附近的默认操作,如下所示:

$("#btnTitleQuery").bind("click", function(evt) {
  // This prevents the form submission.
  evt.preventDefault();

  // Your $.ajax() and rendering code here.
});

2)您不应手动序列化服务方法的返回值并在客户端反序列化它。已经有一层JSON序列化正在发生。而不是从这些方法返回类型字符串,请使用以下内容:

public class Book
{
  public string BookNum { get; set; }
  public string Title { get; set; }
  public string Author { get; set; }
}

[WebMethod(Description = "Gets the books matching part of a title.")]
public List<Book> GetBooksByTitle(string strTitle) {

  OdbcConnection objConnection = new OdbcConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Books"].ConnectionString);

  // Be careful.  You've got a SQL injection vulnerability here.
  OdbcCommand objCommand = new OdbcCommand("SELECT * FROM reading WHERE Title LIKE '%" + strTitle + "%' ORDER BY BookNum;", objConnection);

  DataTable dt = new DataTable();

  OdbcDataAdapter objDataAdapter = new OdbcDataAdapter(objCommand);

  objDataAdapter.Fill(dt);

  objConnection.Close();

  List<Book> result = new List<Book>();

  foreach (DataRow row in dt.Rows)
  {
    result.Add(new Book() {
      BookNum = row["BookNum"].ToString(),
      Title = row["Title"].ToString(),
      Author = row["Author"].ToString()
    });
  }

  return result;
}

然后,您可以通过更改$.ajax()这样的电话来消费它:

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "BookServices.asmx/GetBooksByTitle",
  data: '{ strTitle: "' + $("#txtTitle").val() + '" }',
  dataType: "json",
  success: function(msg) {
    for(var i = 0; i < msg.d.length; i++) {
      // You should avoid accessing the DOM during every loop.
      $("#ResultsTable tr:last").after("<tr><td>" + msg.d[i].BookNum + "</td><td>" + msg.d[i].Title + "</td><td>" + msg.d[i].Author + "</td></tr>");
    }
  }
});

3)最后,这将是一个使用jQuery模板而不是所有字符串连接的好地方。您可以使用这样的简单模板:

<script type="text/x-jquery-tmpl" id="BooksQueryTemplate">
  <table id="ResultsTable" class="BooksTable">
    <tr>
      <th>BookNum</th>
      <th>Title</th>
      <th>Author</th></tr>
    </tr>
    {{each d}}
    <tr>
      <td>${BookNum}</td>
      <td>${Title}</td>
      <td>${Author}</td>
    </tr>
    {{/each}}
  </table>
</script>

然后,在你的$ .ajax()调用中渲染它:

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "BookServices.asmx/GetBooksByTitle",
  data: '{ strTitle: "' + $("#txtTitle").val() + '" }',
  dataType: "json",
  success: function(msg) {
    $('#BooksQueryTemplate').tmpl(msg).appendTo('#query_results');
  }
});