jquery跨域访问Webservice

前端:

<!DOCTYPE HTML>
<meta charset="utf-8">
<html>
<head>
    <title>Canvas</title>
    <script type="text/javascript" src="jquery-1.11.1.js"></script>

    <script type="text/javascript">
        $(document).ready(function()
        {
            //alert('Tessst');
        });
        
         function Click()
        {
            var url = "http://localhost:26562/WebServiceTest.asmx/HelloWorld?jsoncallback=?"
            $.getJSON(url, { userName: null }, function (json) {
                alert(json.Name);
                alert(json.Age);
            });
        }
    </script>
</head>
<h1>Hellow roldw</h1>
<body>
    <input type="button" onclick="Click()">Click me</button>
</body>
</html>

后端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Newtonsoft.Json;

namespace WebApplication2
{
    /// <summary>
    /// Summary description for WebServiceTest
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 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 WebServiceTest : System.Web.Services.WebService
    {

        [WebMethod]
        public void HelloWorld()
        {

            Student stu = new Student();
            stu.Name = "Tom";
            stu.Age = "10";
            string jsoncallback = HttpContext.Current.Request["jsoncallback"];
            string result = jsoncallback + "(" + JsonConvert.SerializeObject(stu) + ")";
            HttpContext.Current.Response.Write(result);
            HttpContext.Current.Response.End();
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public string Age { get; set; }
    }
}

配置Web.config

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
      <httpHandlers>
        <remove verb="*" path=".asmx"/>
        <add verb="*" path=".asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </httpHandlers>
      <webServices>
        <protocols>
          <add
         name="HttpSoap"/>
          <add
        name="HttpPost"/>
          <add
            name="HttpGet"/>
          <add
            name="Documentation"/>
        </protocols>
      </webServices>
      <globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8"/>
    </system.web>

</configuration>

参考:http://www.cnblogs.com/zengqinglei/archive/2012/10/21/2733141.html

posted @ 2014-11-28 11:29  邹邹  Views(151)  Comments(0)    收藏  举报