jQuery跨域

jquery1.2以上版本均支持跨域操作,使用方法是GETJSON

实战演练:

前台代码p1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="p1.aspx.cs" Inherits="test_p1" %>

<!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>
</head>
<body>
</body>
</html>
<script type="text/javascript" src="../js/jQuery_1.42.js"></script>
<script type="text/javascript">
$(function(){
    $.getJSON("http://192.168.0.130/test/p2.aspx?id=100&jsoncallback=?",function(json){
         alert(json)
    });  
})
</script>

后台p2.aspx

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class test_p2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string id = Request.QueryString["id"];
            Response.Write(Request.QueryString["jsoncallback"] + "(" + id + ")");
            Response.End();
        }
    }
}

注意:

    p2.aspx在输出JSON数据时,一定要用Request.QueryString["jsoncallback"],将获取的内容放到返回JSON数据的前面,例如上例中输出 id 的值,getJSON跨域的原理是把?随机变一个方法名,然后返回执行的,实现跨域响应的目的,能用就好。

posted @ 2012-05-08 17:51  WebApi  阅读(282)  评论(1编辑  收藏  举报
CopyRight © 博客园 WebAPI