Ajax跨域访问—Jsonp

Ajax不能跨域访问,现在通过Jsonp 方式可以实现跨域,Jsonp 是json 方式下添加了回调函数


使用Jquery ajax方法,HTML 代码如下

 

目标域:http://localhost:6118/Store/Browse 本地域:http://127.0.0.1:8020/lin/index.html

<html xmlns="http://www.w3.org/1999/xhtml" >  
<head runat="server">  
<meta  meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script src="jquery-1.7.2.js" type="text/javascript"></script>  
<script type="text/javascript">  
  
    function load() {  
    	var data ="m="+$("#text").val(); // m=内容
        $.ajax({  
            url: "http://localhost:6118/Store/Browse",  //跨的目标域
            data: data,
            type: "get",  
            processData: false,  
            timeout: 15000,  
            dataType: "jsonp",   //jsonp形式
            jsonp: "call",  //回调函数
            success: function(result) { //返回响应
            	alert(result.message);//json的内容
            }  
        });  
    }  
   
  
</script>  
    <title></title>  
</head>  
<body>  
		<input id="text" type="text"  />
        <input id="btn" type="button" value="Ajax跨域" onclick="load()" /><br/>       
</body>  
</html>  

 .cs后台代码

 public class StoreController : Controller
 {

        public void Browse(string m)
        {
            string call = Request["call"];    //对应上述回调

            string json ="{\"message\":\""+"跨域返回:"+m+"\"}";  //jsonp格式

            Response.Write(call+"("+json+")");
        }
}

 Json 格式数据 :{"message":"跨域返回:1"}

 Jsonp 格式: call({"message":"跨域返回:1"})

 完成了,简单实例

posted @ 2012-07-21 17:12  Mr.Lin_♪  阅读(213)  评论(0)    收藏  举报