JS跨域提交
ajax可以讓我們對頁面進行無刷新的操作,給我們前端和后台數據交互帶來更多的體驗,這里就不多說了,但ajax也有局限性,由於瀏覽器有安全機制,不 允許我們訪問不同域的數據,也就是我們常說的"同源策略",大家可以去了解一下。但我們有時候又有這樣的需求,下面我們淺談一下,解決這種問題的辦法。
1、jsonp格式
優點:跨域提交
缺點: 只能進行get方式訪問
2、js+form+iframe+php
優點:跨域提交get和post的方式訪問都是可以的
缺點:沒有返回值
jsonp的這種格式非常簡單,而且我前面一篇博客也簡紹了這種方式,之所以介紹第二種,也是因為項目上用到了,而且我也覺得有必要單獨的在把第二種方式拿出來分享一下。
html代碼塊:
<!DOCTYPE html> <html> <head> <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> </style> </head> <body> 用戶名: <input type="text" id="name"> </br> 密碼:<input type="password" id="pwd"> </br> <button type="button" id="subData">提交</button> </body> </html>
Javascript代碼塊:
<script> function smal_send(){ var user=$("#name").val(); var pwd=$("#pwd").val(); //http://localhost/juhe/Managers/DB/kuayu.php 你需要提交數據所到的后台地址 //method="post"則為post方式提交;method="get"則為get方式提交 var form =$("<form action='http://localhost/juhe/Managers/DB/kuayu.php' method='post'>" + "<input type='hidden' name='user_name' value=''/> " + "<input type='hidden' name='password' value=''/> " + "</form> "); $( "#SMAL" ).remove();//如果已存在iframe則將其移除 $( "body").append("<iframe id='SMAL' name='SMAL' style='display: none'></iframe>");//載入iframe (function(){ $( "#SMAL" ).contents().find('body').html(form);//將form表單塞入iframe; $( "#SMAL" ).contents().find("form input[name='user_name']").val(user);//賦值給iframe中表單的文本框中 $( "#SMAL" ).contents().find("form input[name='password']").val(pwd);//賦值給iframe中表單的文本框中 $( "#SMAL" ).contents().find('form').submit();//提交數據 }()); } $(document).ready(function(){ $("#subData").click(function(){ smal_send();//調用函數 }) }) </script>
Php代碼塊:
<?php require_once("DB.php"); $db=new DB(); $com=$_POST["user_name"];//獲取使用的種類 $dataArry=array("comment"=>$com); $flag=$db->Update_Sql("userinfo",$dataArry); ?>
由於使用iframe這種方式沒有結果返回值,所以想要驗證提交是否成功,最好建一張表,然后使用后台將提交得到的值放入數據庫中以此來驗證是否成功!