AJAX跨域解决方案

  从AJAX诞生那天起,XMLHttprequest对象不能跨域请求的问题就一直存在,这似乎是一个很经典的问题了,是由于javascript的同源策略所导致。

解决的办法,大概有如下几种:

1. 使用中间层过渡的方式(可以理解为“代理”)

  中间过渡,就是在AJAX与不同域的服务器进行通讯的中间加一层过渡,这一层过渡可以是PHP、JSP、c++等任何具备网络通讯功能的语言,由中间层向不同域的服务器进行读取数据的操作。拿asp.net做一个例子,如果需要对不同域的某一个asp.net进行通讯,现在客户端的xmlhttprequest先query本域的一个asp.net ,然后由本域的这个asp.net去和不同域的asp.net进行通讯,然后由本域的asp.net响应输出(response)。

2. 使用<script>标签

  这个方法是利用<script>标签中的src来query一个aspx获得response,因为<script>标签的src属性不存在跨域的问题。举个例子:

页面代码:

<!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>
    <title>Ajax跨域问题</title>
    <script type="text/javascript" src="" id="getAspx">
    </script>
    <script type="text/javascript">
        function get(url) {
            var obj = document.getElementById("getAspx");
            obj.src = url;
            (obj.readStatus == 200)
            {
                alert(responseVal);//如果成功,会弹出Dylan
            }
        }
        function query() {
            get(getDemo.aspx);
        }
    </script>
</head>
<body>
<input type="button" value="Ajax跨域测试" onclick="query();"/>
</body>
</html>
View Code

getDemo.aspx后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LearnJS
{
    public partial class getDemo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("var responseVal='Dylan'");
        }
    }
}
View Code

  这个方法又叫做ajaj或者ajax without xmlHttprequest,把x换成了j,是因为使用了<script>标签而没有用到xml和xmlHttprequest的缘故。

3. JQuery解决方法

页面代码:

<html>
<head>
<title>JQuery学习</title>
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
    var oBtnTest = $("#btnTest");
    oBtnTest.click(function(){
        oBtnTest.disabled = true;    
        var oResult = $("#result");
        oResult.html("loading").css("color","red");
        jQuery.getScript("http://www.test.com/test/js.txt", 
        function(){            
            oResult.html("name:" + Dylan.name + "<br/>email:" + Dylan.email).css("color","black");            
            oBtnTest.disabled = false;            
        });         
    });    
});    
</script>
</head>
<body>
<button id="btnTest">BtnTest</button>
<div id="result"></div>
</body>
</html>
View Code

远程服务器端js.txt中的内容为:

var Dylan= {name:"Dylan",email:Dylan@163.com}

原文地址:https://www.cnblogs.com/NichkChang/p/4428119.html