关于JQuery 中$.ajax函数利用jsonp实现Ajax跨域请求ASP.NET的WebService成功获取数据的案例

部署环境:Window 7 SP1+IIS7

成功方案:

其成功解决问题的几个重要因素如下:

1.       由于WebService默认不支持Get请求,所以要在Web.config配置文件内的<system.web>节点内添加如下元素:

 <system.web>
 <webServices>
         <protocols>
           <add name="HttpGet"/>
           <add name="HttpPost"/>
         </protocols>
 </webServices>
 </system.web>

注意:放在web service网站的web.config里面,而不是放在客户端程序的web.config里。

2.       在请求的URL加参数jsoncallback=?,注意这里jsoncallback=?是关键所在!其中?符号会被JQuery自动替换成其它的回调方法名称,具体过程和原理我们这里不予理会。我们关心的是jsoncallback=?起什么作用了?原来jsoncallback=?被替换后,会把方法名称传给服务器。我们在服务器端要做什么工作呢?服务器要接受参数jsoncallback,然后把jsoncallback的值作为JSON数据方法名称返回。

3.       设置dataType类型为”jsonp”

WebService代码如下:

using System.Web;
  using System.Web.Services;
  /// <summary>
  ///UserService 的摘要说明
  /// </summary>
  [WebService(Namespace = "http://tempuri.org/")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  public class UserService : System.Web.Services.WebService
  { 
     [WebMethod]
     public void GetLoginId(string loginId)
     {
         string callback = HttpContext.Current.Request["jsoncallback"];
         bool bl= true;//这是我调用业务逻辑层(BLL)的一个方法
                               //返回一个布尔(boolean)值
                               //现在我省略掉,直接赋值true
         HttpContext.Current.Response.Write(callback +
             "({result:'" + bl + "'})");
         //关于result这词是你自己自定义的属性
         //会作为回调参数的属性供你调用结果
         HttpContext.Current.Response.End();
     }
 }

aspx页面及javascript脚本代码如下:

<%@ 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 type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>
      <script type="text/javascript">
          //Document加载完毕后初始化方法
         $(function Init() {
             $("#TxtLoginId").bind("blur", CkLoginId);
         }); 
         //帐号验证及提示
         function CkLoginId() {
             var Id = $("#TxtLoginId");
             $.ajax({
                 url: "http://localhost:5311/UserService.asmx/GetLoginId?jsoncallback=?",
                 dataType:"jsonp",
                 data:{"loginId":Id.val()},
                 success:OnSuccess,
                 error:OnError
             });
         }
         function OnSuccess(json) {
             alert(json.result);
         }
         function OnError(XMLHttpRequest, textStatus, errorThrown) {
             targetDiv = $("#data");
             if (errorThrown || textStatus == "error" || textStatus == "parsererror" || textStatus == "notmodified") {
                 targetDiv.replaceWith("请求数据时发生错误!");
                 return;
             }
             if (textStatus == "timeout") {
                 targetDiv.replaceWith("请求数据超时!");
                 return;
             }
         }  
     </script>
 </head>
 <body>
     <form id="form1" runat="server">
     <table border="0" cellspacing="0" cellpadding="0" width="100%">
         <tr>
             <td>
                 <asp:Label ID="LblLoginId" runat="server" Text="帐&nbsp;&nbsp;号" ClientIDMode="Static"></asp:Label>
                 <asp:TextBox ID="TxtLoginId" runat="server" ClientIDMode="Static"></asp:TextBox>
             </td>
         </tr>
     </table>
     </form>
 </body>
 </html>

运行结果:

 

原文链接:http://www.cnblogs.com/VAllen/archive/2012/07/12/JQueryAjaxRegion.html

原文地址:https://www.cnblogs.com/jerrywublogs/p/5258613.html