Ajax和Jsonp實踐

之前一直使用jQuery的ajax方法,導致自己對瀏覽器原生的XMLHttpRequest對象不是很熟悉,于是決定自己寫下,以下是個人寫的deom,發表一下,聊表紀念。

Ajax 和 jsonp 的javascript 實現:

/*! 
* ajax.js
* ? auth zernmal 
* @ description XMLHttpRequest and Jsonp practice
*/function ajax(url,options ){var options = options || {} ,method = options.method || "GET",async = (typeof options.async !== "undefined") ? options.async : true ,user = (typeof options.user !== "undefined") ? options.user : "" ,pswd = (typeof options.pswd !== "undefined") ? options.pswd : "" ,reciveType = options.reciveType || "string" ,data = options.data || null ,header = options.header || [],callback = options.callback || function(){},xhr =  XMLHttpRequest ?  new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");if(method=='GET' && data){var dataStr = [];url = (url.indexOf("?")==-1) ? url + "?" : url + "&" ; for(var i in data){dataStr.push( i + "=" + data[i]) ;}url += dataStr.join("&");data = null;}else if(data){var form = new FormData();        for(var i in data){form.append( i , data[i]);    }data = form;}xhr.onreadystatechange = function() {if (xhr.readyState == 4) {// 4 = "loaded"if (xhr.status == 200) {// 200 = OKvar responseData = null ;if(reciveType==="string"){responseData = xhr.responseText;}else if(reciveType === "json"){responseData = xhr.responseText;if( false && JSON && JSON.parse) {responseData = JSON.parse(responseData);}else{responseData = eval('('+responseData+')');}}options.callback && options.callback(responseData);} else {alert("Problem retrieving XML data");}}};xhr.open(method , url , async , user ,pswd);    for(var i = header.length -1 ; i > 0 ; i--){xhr.setRequestHeader(header[i].type, header[i].content);    }xhr.send(data);
}function jsonp(url , options){var options = options || {} ,script = document.createElement('script') ,callback = options.callback || function(result){} ,callbackName = 'myjsonpcall'+ (new Date()).getTime(),data = options.data || {} ,dataStr = [];for(var i in data){dataStr.push( i + "=" + data[i]) ;}if(url.indexOf("?")==-1){url += "?"+ dataStr.join("&") +"&callback="+callbackName;}else{url += "&"+ dataStr.join("&") +"&callback="+callbackName;}script.setAttribute('src', url);    window[callbackName] = callback ;// 把script標簽加入head,此時調用開始document.getElementsByTagName('head')[0].appendChild(script);
}

PHP服務端響應請求:

<?php$func = $_GET['func'];if(function_exists($func)){$func();}else{funcNotExist();}function funcNotExist(){echo "function is not exist ! ";}function returnJson(){$lastName = $_GET['lastName'];$firstName = $_GET['firstName'];echo json_encode(array('firstName'=>$firstName,'lastName'=>$lastName));}function returnString(){$lastName = $_GET['lastName'];$firstName = $_GET['firstName'];echo "the string you send is ".$lastName." ".$firstName;}function postReturn(){$lastName = $_POST['lastName'];$firstName = $_POST['firstName'];echo "the string you post is ".$lastName." ".$firstName;}function jsonP(){header('content-type: application/json; charset=utf-8');$lastName = $_GET['lastName'];$firstName = $_GET['firstName'];$callbackFunc = isset($_GET['callback'])? htmlspecialchars($_GET['callback']):"callback";$json = json_encode(array('firstName'=>$firstName,'lastName'=>$lastName));echo "$callbackFunc($json)";}

頁面內調用方法:

<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Ajax與Jsonp實踐</title><script type="text/javascript" src="js/ajax.js"></script>
</head>
<body>
<script>jsonp("/ajax.php?func=jsonP",{callback : function(result){console.log(result);},data : {lastName : "zernmal" , firstName : "chen"} 
});ajax("/ajax.php?func=returnJson",{method : "GET",callback : function(result){console.log(result);},data : {lastName : "zernmal" , firstName : "chen"} ,reciveType : "json"
});
</script>
</body>
</html>

以上只是簡單實驗,如有問題歡迎提出。

轉載于:https://www.cnblogs.com/zernmal/p/3751066.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/376975.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/376975.shtml
英文地址,請注明出處:http://en.pswp.cn/news/376975.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

得到前i-1個數中比A[i]小的最大值,使用set,然后二分查找

題目 有一個長度為 n 的序列 A&#xff0c;A[i] 表示序列中第 i 個數(1<i<n)。她定義序列中第 i 個數的 prev[i] 值 為前 i-1 個數中比 A[i] 小的最大的值&#xff0c;即滿足 1<j<i 且 A[j]<A[i] 中最大的 A[j]&#xff0c;若不存在這樣的數&#xff0c;則 pre…

學習語言貴在堅持

學習語言貴在堅持 轉自&#xff1a;http://zhidao.baidu.com/link?urlr2W_TfnRwipvCDLrhZkATQxdrfghXFpZhkLxqH1oUapLOr8jXW4tScbyOKRLEPVGCx0dUfIr-30n9XV75pWYfK給大家介紹幾本書和別處COPY來的學習C50個觀點 《Thinking In C》&#xff1a;《C編程思想》&#xff1b; 《The…

stl vector 函數_在C ++ STL中使用vector :: begin()和vector :: end()函數打印矢量的所有元素...

stl vector 函數打印向量的所有元素 (Printing all elements of a vector) To print all elements of a vector, we can use two functions 1) vector::begin() and vector::end() functions. 要打印矢量的所有元素&#xff0c;我們可以使用兩個函數&#xff1a;1) vector :: b…

JqueryUI入門

Jquery UI 是一套開源免費的、基于Jquery的插件&#xff0c;在這里記錄下Jquery UI 的初步使用。 第一、下載安裝 下載Jquery,官網&#xff1a;http://jquery.com;  下載Jquery UI&#xff0c;官網&#xff1a;http://jqueryui.com/ Jquery的部署就不說了&#xff0c;說下Jqu…

gp的分布、分區策略(概述)

對于大規模并行處理數據庫來說&#xff0c;一般由單master與多segment組成。 那么數據表的單行會被分配到一個或多個segment上&#xff0c;此時需要想一想分布策略 分布 在gp6中&#xff0c;共有三個策略&#xff1a; 哈希分布 隨機分布 復制分布 哈希分布 就是對分布鍵進行…

[ Java4Android ] Java基本概念

視頻來自&#xff1a;http://www.marschen.com/ 1.什么是環境變量 2.JDK里面有些什么&#xff1f; 3.什么是JRE&#xff1f; 什么是環境變量&#xff1f; 1.環境變量通常是指在操作系統當中&#xff0c;用來指定操作系統運行時需要的一些參數; 2.環境變量通常為一系列的鍵值對&…

_thread_in_vm_Java Thread類的靜態void sleep(long time_in_ms,int time_in_ns)方法,帶示例

_thread_in_vm線程類靜態無效睡眠(long time_in_ms&#xff0c;int time_in_ns) (Thread Class static void sleep(long time_in_ms, int time_in_ns)) This method is available in package java.lang.Thread.sleep(long time_in_ms, int time_in_ns). 軟件包java.lang.Thread…

大規模web服務開發技術(轉)

前段時間趁空把《大規模web服務開發技術》這本書看完了&#xff0c;今天用一下午時間重新翻了一遍&#xff0c;把其中的要點記了下來&#xff0c;權當復習和備忘。由于自己對數據壓縮、全文檢索等還算比較熟&#xff0c;所以筆記內容主要涉及前5章內容&#xff0c;后面的零星記…

IO多路復用的三種機制Select,Poll,Epoll

IO多路復用的本質是通過系統內核緩沖IO數據讓單個進程可以監視多個文件描述符&#xff0c;一旦某個進程描述符就緒(讀/寫就緒)&#xff0c;就能夠通知程序進行相應的讀寫操作。 select poll epoll都是Linux提供的IO復用方式&#xff0c;它們本質上都是同步IO&#xff0c;因為它…

qt中按鈕貼圖

一.QT之QPushButton按鈕貼圖 二.QT之QToolButton按鈕貼圖 一.QT之QPushButton按鈕貼圖具體操作流程 1. Qt Designer中拖入一Tool Button 2. 選擇圖標的圖片放入工程目錄下&#xff0c;如放在Resources內 3. 雙擊工程的Resource Files下的qrc文件&#xff0c;如圖 4. 在彈出的窗…

Ubuntu手動編譯gVim7.3修復終端啟動時與ibus的沖突

個bug伴隨著Ubuntu/ibus的升級苦憋已久&#xff0c;癥狀為終端啟動gvim時卡死&#xff0c;gvim -f可以緩解此問題&#xff0c;但偶爾還是要發作&#xff0c;況且每次末尾托個&也不方便。其實新版gvim已經修復此bug&#xff0c;不過ubuntu安裝包一直沒更新&#xff0c;那我們…

Android Activity類講解(一)

--by CY[kotomifigmail.com] &#xff11;&#xff0e;protected void onCreate(Bundle savedInstanceState) { throw new RuntimeException("Stub!");   } 當創建一個Activity時&#xff0c;系統會自動調用onCreate方法來完成創建工作&#xff0e;該創建工作包括布…

Mysql的undo、redo、bin log分析

目錄關于undo log關于redolog關于binlog一個事務的提交流程undo log :記錄數據被修改之前的樣子 redo log&#xff1a;記錄數據被修改之后的樣子 bin log&#xff1a;記錄整個操作。 關于undo log 關于undo log&#xff1a; 在執行一條涉及數據變更的sql時&#xff0c;在數據…

typedef 字符串_typedef在C中使用字符數組(定義別名來聲明字符串)的示例

typedef 字符串Here, we have to define an alias for a character array with a given number of maximum characters length to read strings? 在這里&#xff0c;我們必須為具有給定最大字符長度數的字符數組定義別名&#xff0c;以讀取字符串 &#xff1f; In the below-…

最小堆實現代碼

參考算法導論、數據結構相關書籍&#xff0c;寫得最小堆實現的源代碼如下&#xff1a; 1 //2 //--最小堆實例3 //4 5 #include <iostream>6 #include <vector>7 #include <string>8 using namespace std;9 10 template<typename Comparable>11 class m…

非常好的在網頁中顯示pdf的方法

今天有一需求&#xff0c;要在網頁中顯示pdf&#xff0c;于是立馬開始搜索解決方案&#xff0c;無意中發現一個非常好的解決方法&#xff0c;詳見http://blogs.adobe.com/pdfdevjunkie/web_designers_guide。 其實就光看這個網站也足夠了&#xff0c;http://www.pdfobject.com/…

Redis字典實現、Hash鍵沖突以及漸進式rehash

本筆記參考《Redis設計與實現》 P24~ 37 目錄Redis字典實現哈希表節點結構哈希表結構字典哈希算法解決hash沖突rehash漸進式hashRedis字典實現 哈希表節點結構 typedef struct dictEntry {// 鍵void *key;// 值 : 可以是一個指針&#xff0c;或者是一個uint64/int64 的整數un…

Java線程類void setContextClassLoader(ClassLoader loader)方法,帶示例

線程類void setContextClassLoader(ClassLoader loader) (Thread Class void setContextClassLoader(ClassLoader loader)) This method is available in package java.lang.Thread.setContextClassLoader(ClassLoader loader). 軟件包java.lang.Thread.setContextClassLoader(…

JPA概要

本文最新版已更新至&#xff1a;http://thinkinside.tk/2012/12/30/JPA.html JPA定義了Java ORM及實體操作API的標準。本文摘錄了JPA的一些關鍵信息以備查閱。 如果有hibernate的基礎&#xff0c;通過本文也可以快速掌握JPA的基本概念及使用。 Table of Contents 1 JPA概述2 實…

如何配置能讓fiddler抓去https的請求?

1、打開fiddler&#xff0c;>>Tools>>Fiddler Options&#xff0c; 打開如圖所示的HTTPS配置項&#xff1a;點擊Export Rppt Certifica to Desktop :桌面上多了一個證書&#xff1a;下面就是將證書導入&#xff1a;點擊開始-運行&#xff0c;輸入&#xff1a;mmc,…