jquery jsonp请求asp.net webservice

  使用jquery的jsonp请求asp.net的webservice时,由于webservice一般返回的数据格式为xml或者只包含一个d属性的json(设置ajax请求的contentType为application/json)对象,具体参考:jquery webservice

 

  如果想指定jquery的ajax为jsonp请求,需要调用Response对象输出原始的内容,调用的方法返回值申明为void。示例代码如下,注意asp.net的webservice要配置允许get/post访问。

web.config增加

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

test.asmx

        [WebMethod]
        public void JQueryJsonp(string callback)
        {
            System.Web.HttpContext.Current.Response.Write(callback+"({username:'showbo'})");
            System.Web.HttpContext.Current.Response.End();
        }

jquery代码

    $.ajax({
        url: "test.asmx/JQueryJsonp?callback=?",
        dataType: "jsonp",
        success: function (json) { alert("Success:" + json.username); },
        error: function (x, e) { alert("Error:" + x.responseText); }, 
        complete: function (x) { alert("Complete:" + x.responseText); }
    });

jquery jsonp请求asp.net webservice

加支付宝好友偷能量挖...


原创文章,转载请注明出处:jquery jsonp请求asp.net webservice

评论(0)Web开发网
阅读(647)喜欢(0)Asp.Net/C#/WCF