標籤:jquery ajax html5 app開發 access-control-allow
初識JQuery AJAXAPP開發群:347072638(HTML5,APP)
1.先看一個JQuery AJAX Demo
HTML端:
<!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></title> <script src="js/jquery-1.9.1.min.js" type="text/javascript"></script> <script type="text/javascript" language="javascript"> $(document).ready(function () { jQuery.support.cors = true; $('#JQuery_AJAX_Test').click(function () { $.ajax({ type: "POST", url: "http://version.messageloop.net/index.php", data: "{ version: 1}", dataType: "json", success: function(data, textStatus, jqXHR){ alert("code:"+data.code+"\nresult:"+data.message+"\ntextStatus:"+textStatus+"\njqXHR:"+jqXHR); } }); }); }); </script></head><body> <a href="#" id="JQuery_AJAX_Test">JQuery AJAX Test</a><br/> <div id="result"></div></body></html>
PHP服務端:
<span style="font-size:12px;"><?php$output = array();$deviceType = @$_GET['deviceType'] ? $_GET['deviceType'] : '';$version = @$_GET['version'] ? $_GET['version'] : 0;header('Access-Control-Allow-Origin: *'); //註:這個地方很重要。<span style="font-family: Verdana, Arial, 宋體; line-height: 18px; background-color: rgb(249, 249, 249);">由於瀏覽器安全方面的限制,大多數 "Ajax" 請求遵守同源策略;請求無法從不同的域、子域或協議成功地取回資料。</span>define('ROOT', dirname(__FILE__));$file = ROOT . '/open_device_config';$content = file_get_contents($file);//deviceType must equal 'android' and version 大於配製檔案版本號碼才提示OK!if ($deviceType == 'android' && $version <= $content){$output = array('code'=>201, 'message'=>'This version can not use, you must up grade!'); exit(json_encode($output));}else{ $output = array('code'=>200, 'message'=>'This version is OK!'); exit(json_encode($output));}?></span>
效果:
2.什麼是 AJAX?AJAX = 非同步 JavaScript 和 XML(Asynchronous JavaScript and XML)。AJAX就是與伺服器做資料交換的,可以對網頁實現局部更新。
3.什麼是JQuery AJAX?
JQuery對AJAX進行了一層封裝。通過 jQuery AJAX 方法,您能夠使用 HTTP Get 和 HTTP Post 從遠程伺服器上請求文本、HTML、XML 或 JSON - 同時您能夠把這些外部資料直接載入網頁的被選元素中。
4.如何使用JQuery AJAX?
文法:
jQuery.post(url,data,success(data, textStatus, jqXHR),dataType)
| 參數 |
描述 |
| url |
必需。規定把請求發送到哪個 URL。 |
| data |
可選。映射或字串值。規定連同請求發送到伺服器的資料。 |
| success(data, textStatus, jqXHR) |
可選。請求成功時執行的回呼函數。 |
| dataType |
可選。規定預期的伺服器響應的資料類型。
預設執行智能判斷(xml、json、script 或 html)。 |
詳細說明
該函數是簡寫的 Ajax 函數,等價於:
$.ajax({ type: ‘POST‘, url: url, data: data, success: success, dataType: dataType});
5.注意事項
由於瀏覽器安全方面的限制,大多數 "Ajax" 請求遵守同源策略;請求無法從不同的域、子域或協議成功地取回資料。如果在不同域下訪問就會出現提示:
No ‘Access-Control-Allow-Origin‘ header is present on the requested resource. Origin ‘http://127.0.0.1‘ is therefore not allowed access.
因此解決方案:
1.採用同域策略,在同一網域名稱下。
2.在服務端設定屬性,如:php服務端,header(‘Access-Control-Allow-Origin: *‘);
APP開發群:347072638(HTML5,APP)