使用jsonp实现ajax跨域请求

时间:2022-05-25 01:00:09
Jsonp(JSON with Padding)是资料格式 json 的一种“使用模式”,可以让网页从别的网域获取资料。
由于同源策略,一般来说位于 server1.example.com 的网页无法与不是 server1.example.com的服务器沟通,而 HTML 的<script> 元素是一个例外。利用 <script> 元素的这个开放策略,网页可以得到从其他来源动态产生的 JSON 资料,而这种使用模式就是所谓的 JSONP。用 JSONP 抓到的资料并不是 JSON,而是任意的JavaScript,用 JavaScript 直译器执行而不是用 JSON 解析器解析。
 

JSONP的优点是:

它不像XMLHttpRequest对象实现的Ajax请求那样受到同源策略的限制;它的兼容性更好,在更加古老的浏览器中都 可以运行,不需要XMLHttpRequest或ActiveX的支持;并且在请求完毕后可以通过调用callback的方式回传结果。

JSONP的缺点则是:

它只支持GET请求而不支持POST等其它类型的HTTP请求;它只支持跨域HTTP请求这种情况,不能解决不同域的两个页面之间如何进行JavaScript调用的问题。

JSONP是一种脚本注入(Script Injection)行为,有一定的安全隐患。

下面说说如何实现:

一、首先需要在你的webservice的web.config中system.web节点里加入以下节点:

<webServices>

      <protocols>

        <add name="HttpPost"/>

        <add name="HttpGet"/>

      </protocols>

    </webServices>

二、webservice代码,为了同时支持一般的请求与jsonp ajax请求,代码如下:

using System.Web.Services;
using System.Collections.Generic;
using System.Data;
using System.Web; /// <summary>
///WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
/// <summary>
/// 在ajax请求返回后,会自动将这些类型转换为json对象
/// </summary>
public WebService()
{
} [WebMethod(Description = "测试")]
public string getInfos(string infostring)
{
string result = infostring;//所要返回的json数据
string jsonCallBackFunName = HttpContext.Current.Request.Params["jsoncallback"] + "";
if (string.IsNullOrEmpty(jsonCallBackFunName))
{
HttpContext.Current.Response.ContentType = "application/json;charset=utf-8";
HttpContext.Current.Response.Write(jsonCallBackFunName + "(" + infostring + ")");
HttpContext.Current.Response.End();
}
return result;
}
}

三、页面及js代码:

<!DOCTYPE html>

<html>

<head>

    <title>Index</title>

    <script src="jquery-1.8.3.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(function () {

            $("#tj").click(function () {

                var dataStr = "info=ABCTest";

                $.ajax({

                    type: "get",

                    url: http://xxx/jQueryMobile.asmx/getInfos?jsoncallback,

                    dataType: "jsonp",

                    jsonp: 'jsoncallback',

                    data: dataStr,

                    success: function (result) {

                        alert(result.xxx);

                    }

                });

            });

        });

    </script>

</head>

<body>

    <div>

        <input id="tj" type="button" value="提交" />

    </div>

</body>

</html> 

如果遇到类似:Error... parsererror jQuery15001997238997904205_1298484897373 was not called

说明是解析出问题了,我一开始也碰到了,这个很有可能是你服务端返回的json格式有问题,或者拼接出问题了。