jquery post get 跨域 提交資料

來源:互聯網
上載者:User
[轉載 jquery post 跨域 提交資料2011-06-28 11:10

跨域的N種形式:

1.直接用jquery中$.getJSON進行跨域提交

          優點:有傳回值,可直接跨域;

          缺點:資料量小;

   提交方式:僅get (無$.postJSON)

2.在頁面中嵌入一個iframe,把iframe的寬和高設定為0進行跨域提交

           優點:可直接跨域;

           缺點:無傳回值(脫離ajax本質);

    提交方式:get/post

3.直接用$.post跨域,先提交到本地區名下一個代理程式,通過代理程式向目的網域名稱進行post或get提交,並根據目的網域名稱的傳回值通過代理 程式返回給本地頁面

          優點:有傳回值,可直接跨域,可通過 代理程式 統計ip等使用者資訊,增加安全性;

   提交方式:get/post

       複雜度:需要前端工程師和後端工程師配合(php/java../工程師)  

           缺點:需要消耗本機伺服器資源,增加ajax等待時間(可忽略)

4.向百度學習的思路:由於調用任何js檔案不涉及跨域問題,所以js指令碼中可以編寫調用遠程伺服器上的js檔案,該檔案實現你需要的業務。

                                  即a.js動態調用www.baidu.com/b.js ,其中b.js實現業務

5.待研究......

 

 

1.使用post提交方式

2.構造表單的數格式

3.結合form表單的submit調用ajax的回呼函數。

代碼:

使用 jQuery 非同步提交表單

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>無標題頁</title>
</head>
<script src="js/jquery-1.4.2.js"></script>
<script>
jQuery(function($) {
// 使用 jQuery 非同步提交表單
$('#f1').submit(function() {
$.ajax({
url: 'ta.aspx',
data: $('#f1').serialize(),
type: "post",
cache : false,
success: function(data)
{alert(data);}
});
return false;
});
});

</script>
<body>
<form id="f1" name="f1">
<input name="a1" />
<input name="a2" />
<input id="File1" type="file" name="File1"/>
<input id="Submit1" type="submit" value="submit" />
</form>
</body>
</html>

如何非同步跨域提交表單呢?

1.利用script 的跨域訪問特性,結合form表單的資料格式化,所以只能採用get方式提交,為了安全,瀏覽器是不支援post跨域提交的。

2.採用JSONP跨域提交表單是比較好的解決方案。

3.也可以動態程式做一代理。用代理中轉跨域請求。

 代碼:

使用 jQuery 非同步跨域提交表單

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>無標題頁</title>
</head>
<script src="js/jquery-1.4.2.js"></script>
<script>
jQuery(function($)
{
// 使用 jQuery 非同步跨域提交表單
$('#f1').submit(function()
{
$.getJSON("ta.aspx?"+$('#f1').serialize()+"&jsoncallback=?",
function(data)
{
alert(data);
});
return false;
});
});

</script>
<body>
<form id="f1" name="f1">
<input name="a1" />
<input name="a2" />
<input id="File1" type="file" name="File1"/>
<input id="Submit1" type="submit" value="submit" />
</form>
</body>
</html>

補充:方法1不能實現跨越提交。

注意:輸出json格式{'a1','a1value','a2':'a2value'}

字元必須用引號包住,數字可以不加引號。如:{'a1',10,'a2':20}

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.