2011-12-19 237 views
601

如何在不使用jQuery的情況下使用JavaScript進行AJAX調用?如何在沒有jQuery的情況下進行AJAX調用?

+11

之前請注意,雖然有很多的答案這裏建議監聽_readystatechange_,現在的瀏覽器現在支持_XMLHttpRequest_的_load_,_abort_,_progress_和_error_事件雖然只關心_load_雖然)。 – 2015-03-31 16:27:18

+1

@ImadoddinIbnAlauddin例如當它的主要功能(DOM遍歷)不需要時。 – SET 2015-07-10 22:05:35

+3

@Imad是因爲JQuery是一個Javascript庫,當人們決定使用完全非強制性的語言,而且實際上並沒有爲該語言添加任何新東西時,這真是令人討厭。 – DaemonOfTheWest 2015-12-27 21:51:42

回答

33
var xhReq = new XMLHttpRequest(); 
xhReq.open("GET", "sumGet.phtml?figure1=5&figure2=10", false); 
xhReq.send(null); 
var serverResponse = xhReq.responseText; 
alert(serverResponse); // Shows "15" 

http://ajaxpatterns.org/XMLHttpRequest_Call

+2

這項工作將跨瀏覽器? – Benubird 2013-04-26 16:55:50

+49

不要做同步呼叫。使用xhReq.onload並使用回調。 – 2013-05-05 20:52:11

+1

@kenansulayman你能舉例說明你的意思嗎? – 2013-10-26 22:29:28

499

以 「香草」 的JavaScript:

<script type="text/javascript"> 
function loadXMLDoc() { 
    var xmlhttp = new XMLHttpRequest(); 

    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4 
      if (xmlhttp.status == 200) { 
       document.getElementById("myDiv").innerHTML = xmlhttp.responseText; 
      } 
      else if (xmlhttp.status == 400) { 
       alert('There was an error 400'); 
      } 
      else { 
       alert('something else other than 200 was returned'); 
      } 
     } 
    }; 

    xmlhttp.open("GET", "ajax_info.txt", true); 
    xmlhttp.send(); 
} 
</script> 

使用jQuery:

$.ajax({ 
    url: "test.html", 
    context: document.body, 
    success: function(){ 
     $(this).addClass("done"); 
    } 
}); 
+809

請停止支持IE5/IE6 – Archibald 2013-08-14 13:23:52

+3

@DrewNoakes:它絕對更具可讀性,但不幸的是,當我在Opera Mini瀏覽器上嘗試它時,它不被支持,所以我猜 它的支持不太普及 – BornToCode 2014-05-18 21:09:56

+0

@Fractaliste如果你只是在與xmlhttp.status有關的if塊之後調用回調,然後在那裏給他們打電話,你就完成了。 – Jay 2015-06-18 20:30:52

4
<html> 
    <script> 
    var xmlDoc = null ; 

    function load() { 
    if (typeof window.ActiveXObject != 'undefined') { 
     xmlDoc = new ActiveXObject("Microsoft.XMLHTTP"); 
     xmlDoc.onreadystatechange = process ; 
    } 
    else { 
     xmlDoc = new XMLHttpRequest(); 
     xmlDoc.onload = process ; 
    } 
    xmlDoc.open("GET", "background.html", true); 
    xmlDoc.send(null); 
    } 

    function process() { 
    if (xmlDoc.readyState != 4) return ; 
    document.getElementById("output").value = xmlDoc.responseText ; 
    } 

    function empty() { 
    document.getElementById("output").value = '<empty>' ; 
    } 
</script> 

<body> 
    <textarea id="output" cols='70' rows='40'><empty></textarea> 
    <br></br> 
    <button onclick="load()">Load</button> &nbsp; 
    <button onclick="empty()">Clear</button> 
</body> 
</html> 
2

HTML:

<!DOCTYPE html> 
    <html> 
    <head> 
    <script> 
    function loadXMLDoc() 
    { 
    var xmlhttp; 
    if (window.XMLHttpRequest) 
     {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
     } 
    else 
     {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
    xmlhttp.onreadystatechange=function() 
     { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
     document.getElementById("myDiv").innerHTML=xmlhttp.responseText; 
     } 
     } 
    xmlhttp.open("GET","1.php?id=99freebies.blogspot.com",true); 
    xmlhttp.send(); 
    } 
    </script> 
    </head> 
    <body> 

    <div id="myDiv"><h2>Let AJAX change this text</h2></div> 
    <button type="button" onclick="loadXMLDoc()">Change Content</button> 

    </body> 
    </html> 

PHP:

<?php 

$id = $_GET[id]; 
print "$id"; 

?> 
+0

單行ifs不需要大括號,沒有人使用IE6,這可能是複製粘貼,使用onload而不是onreadystatechange,爲可能的遞歸調用捕獲錯誤,xmlhttp是一個可怕的變量名稱,只是稱它爲x。 – super 2015-12-21 10:00:16

186

使用下面的代碼片段,你可以很輕鬆地做類似的事情,就像這樣:

ajax.get('/test.php', {foo: 'bar'}, function() {}); 

下面是摘錄:

var ajax = {}; 
ajax.x = function() { 
    if (typeof XMLHttpRequest !== 'undefined') { 
     return new XMLHttpRequest(); 
    } 
    var versions = [ 
     "MSXML2.XmlHttp.6.0", 
     "MSXML2.XmlHttp.5.0", 
     "MSXML2.XmlHttp.4.0", 
     "MSXML2.XmlHttp.3.0", 
     "MSXML2.XmlHttp.2.0", 
     "Microsoft.XmlHttp" 
    ]; 

    var xhr; 
    for (var i = 0; i < versions.length; i++) { 
     try { 
      xhr = new ActiveXObject(versions[i]); 
      break; 
     } catch (e) { 
     } 
    } 
    return xhr; 
}; 

ajax.send = function (url, callback, method, data, async) { 
    if (async === undefined) { 
     async = true; 
    } 
    var x = ajax.x(); 
    x.open(method, url, async); 
    x.onreadystatechange = function() { 
     if (x.readyState == 4) { 
      callback(x.responseText) 
     } 
    }; 
    if (method == 'POST') { 
     x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); 
    } 
    x.send(data) 
}; 

ajax.get = function (url, data, callback, async) { 
    var query = []; 
    for (var key in data) { 
     query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); 
    } 
    ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async) 
}; 

ajax.post = function (url, data, callback, async) { 
    var query = []; 
    for (var key in data) { 
     query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); 
    } 
    ajax.send(url, callback, 'POST', query.join('&'), async) 
}; 
+1

這是一個非常棒的jumpstart,但我認爲你錯過了@ 3nigma答案中的某些功能。也就是說,我不確定在沒有返回服務器響應的情況下做出某些請求(全部獲得併發布一些帖子)是多少意義。我在send方法的末尾添加了另一行 - 'return x.responseText;' - 然後返回每個'ajax.send'調用。 – Sam 2014-08-13 10:37:38

+2

@Sam [通常]不能返回其異步請求。您應該在回調中處理回覆。 – Petah 2014-08-13 11:18:16

+0

@Sam裏面有一個例子:'ajax.get('/ test.php',{foo:'bar'},function(responseText){alert(responseText);});' – Petah 2014-08-13 21:22:10

85

你可以使用以下功能:

function callAjax(url, callback){ 
    var xmlhttp; 
    // compatible with IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function(){ 
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200){ 
      callback(xmlhttp.responseText); 
     } 
    } 
    xmlhttp.open("GET", url, true); 
    xmlhttp.send(); 
} 

您可以在這些鏈接在線嘗試類似的解決方案:

+0

也可以爲請求添加一些輸入變量(將用於xmlhttp.send(request);) – 2016-10-18 10:43:09

+0

@PavelPerna,因爲這裏的示例是一個'GET',因此您可以將它們添加到請求中,但是更一般的是,我和你在一起,我真的想過更新答案,接受請求參數作爲函數的參數,還要傳遞方法('GET'或'POST'),但是阻止了我我希望這裏的答案儘可能簡單,讓人們儘可能快地嘗試。其實,我討厭太長時間太長的一些其他答案,因爲他們正試圖做到完美:) – AbdelHady 2016-10-19 14:11:21

26

您可以根據瀏覽器得到正確的對象

function getXmlDoc() { 
    var xmlDoc; 

    if (window.XMLHttpRequest) { 
    // code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlDoc = new XMLHttpRequest(); 
    } 
    else { 
    // code for IE6, IE5 
    xmlDoc = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 

    return xmlDoc; 
} 

有了正確的對象,一個GET可能可以抽象爲:

function myGet(url, callback) { 
    var xmlDoc = getXmlDoc(); 

    xmlDoc.open('GET', url, true); 

    xmlDoc.onreadystatechange = function() { 
    if (xmlDoc.readyState === 4 && xmlDoc.status === 200) { 
     callback(xmlDoc); 
    } 
    } 

    xmlDoc.send(); 
} 

和後到:

function myPost(url, data, callback) { 
    var xmlDoc = getXmlDoc(); 

    xmlDoc.open('POST', url, true); 
    xmlDoc.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

    xmlDoc.onreadystatechange = function() { 
    if (xmlDoc.readyState === 4 && xmlDoc.status === 200) { 
     callback(xmlDoc); 
    } 
    } 

    xmlDoc.send(data); 
} 
7

這可能會幫助:

function doAjax(url, callback) { 
    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); 

    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
      callback(xmlhttp.responseText); 
     } 
    } 

    xmlhttp.open("GET", url, true); 
    xmlhttp.send(); 
} 
13

從幾下面的例子小組合創建了這個簡單的作品:

function ajax(url, method, data, async) 
{ 
    method = typeof method !== 'undefined' ? method : 'GET'; 
    async = typeof async !== 'undefined' ? async : false; 

    if (window.XMLHttpRequest) 
    { 
     var xhReq = new XMLHttpRequest(); 
    } 
    else 
    { 
     var xhReq = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 


    if (method == 'POST') 
    { 
     xhReq.open(method, url, async); 
     xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
     xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest"); 
     xhReq.send(data); 
    } 
    else 
    { 
     if(typeof data !== 'undefined' && data !== null) 
     { 
      url = url+'?'+data; 
     } 
     xhReq.open(method, url, async); 
     xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest"); 
     xhReq.send(null); 
    } 
    //var serverResponse = xhReq.responseText; 
    //alert(serverResponse); 
} 

// Example usage below (using a string query): 

ajax('http://www.google.com'); 
ajax('http://www.google.com', 'POST', 'q=test'); 

或者如果你的參數是對象(S) - 未成年人額外的代碼調整:

var parameters = { 
    q: 'test' 
} 

var query = []; 
for (var key in parameters) 
{ 
    query.push(encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key])); 
} 

ajax('http://www.google.com', 'POST', query.join('&')); 

雙方應充分瀏覽器+版本兼容。

+0

這裏值得在for循環中使用hasOwnProperty嗎? – kibibu 2015-02-13 00:05:53

15

我正在尋找包括承諾與Ajax和排除jQuery。有關於HTML5 Rocks的文章介紹了ES6承諾(可以用Q之類的承諾庫進行填充),然後使用我從文章中複製的代碼片段。

function get(url) { 
    // Return a new promise. 
    return new Promise(function(resolve, reject) { 
    // Do the usual XHR stuff 
    var req = new XMLHttpRequest(); 
    req.open('GET', url); 

    req.onload = function() { 
     // This is called even on 404 etc 
     // so check the status 
     if (req.status == 200) { 
     // Resolve the promise with the response text 
     resolve(req.response); 
     } 
     else { 
     // Otherwise reject with the status text 
     // which will hopefully be a meaningful error 
     reject(Error(req.statusText)); 
     } 
    }; 

    // Handle network errors 
    req.onerror = function() { 
     reject(Error("Network Error")); 
    }; 

    // Make the request 
    req.send(); 
    }); 
} 

注:我也寫了an article about this

+0

這是真正有用的,因爲我正在做一個遞歸的長輪詢機制! – super 2015-12-21 09:52:39

12

如果你不想包含JQuery,我會嘗試一些輕量級的AJAX庫。

我的最愛是reqwest。這只是3.4kb和很好的建立了:https://github.com/ded/Reqwest

下面是與reqwest樣本GET請求:

reqwest({ 
    url: url, 
    method: 'GET', 
    type: 'json', 
    success: onSuccess 
}); 

現在,如果你想要的東西更輕巧,我想嘗試microAjax在僅僅0.4kb: https://code.google.com/p/microajax/

這是對這裏的所有代碼:

function microAjax(B,A){this.bindFunction=function(E,D){return function(){return E.apply(D,[D])}};this.stateChange=function(D){if(this.request.readyState==4){this.callbackFunction(this.request.responseText)}};this.getRequest=function(){if(window.ActiveXObject){return new ActiveXObject("Microsoft.XMLHTTP")}else{if(window.XMLHttpRequest){return new XMLHttpRequest()}}return false};this.postBody=(arguments[2]||"");this.callbackFunction=A;this.url=B;this.request=this.getRequest();if(this.request){var C=this.request;C.onreadystatechange=this.bindFunction(this.stateChange,this);if(this.postBody!==""){C.open("POST",B,true);C.setRequestHeader("X-Requested-With","XMLHttpRequest");C.setRequestHeader("Content-type","application/x-www-form-urlencoded");C.setRequestHeader("Connection","close")}else{C.open("GET",B,true)}C.send(this.postBody)}}; 

下面是一個示例調用:

microAjax(url, onSuccess); 
+1

我認爲microAjax存在一個問題,當你調用它兩次(因爲衆多的「this」,我認爲必須有碰撞)。 我不知道如果調用兩個「新的microAjax」是一個很好的解決方法,是嗎? – 2015-05-24 13:47:28

0
在瀏覽器中普通的JavaScript

var xhr = new XMLHttpRequest(); 

xhr.onreadystatechange = function() { 
    if (xhr.readyState == XMLHttpRequest.DONE) { 
    if(xhr.status == 200){ 
     console.log(xhr.responseText); 
    } else if(xhr.status == 400) { 
     console.log('There was an error 400'); 
    } else { 
     console.log('something else other than 200 was returned'); 
    } 
    } 
} 

xhr.open("GET", "mock_data.json", true); 

xhr.send(); 

或者,如果你想使用Browserify捆綁你的模塊使用起來node.js中您可以使用superagent

var request = require('superagent'); 
var url = '/mock_data.json'; 

request 
    .get(url) 
    .end(function(err, res){ 
    if (res.ok) { 
     console.log('yay got ' + JSON.stringify(res.body)); 
    } else { 
     console.log('Oh no! error ' + res.text); 
    } 
}); 
1

這裏有一個JSFiffle不JQuery的

http://jsfiddle.net/rimian/jurwre07/

function loadXMLDoc() { 
    var xmlhttp = new XMLHttpRequest(); 
    var url = 'http://echo.jsontest.com/key/value/one/two'; 

    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == XMLHttpRequest.DONE) { 
      if (xmlhttp.status == 200) { 
       document.getElementById("myDiv").innerHTML = xmlhttp.responseText; 
      } else if (xmlhttp.status == 400) { 
       console.log('There was an error 400'); 
      } else { 
       console.log('something else other than 200 was returned'); 
      } 
     } 
    }; 

    xmlhttp.open("GET", url, true); 
    xmlhttp.send(); 
}; 

loadXMLDoc(); 
4

那麼它只是一個4步輕鬆proceess,

我希望它幫助

Step 1.商店參考XMLHttpRequest對象

var xmlHttp = createXmlHttpRequestObject(); 

Step 2.檢索XMLHttpRequest對象

function createXmlHttpRequestObject() { 
    // will store the reference to the XMLHttpRequest object 
    var xmlHttp; 
    // if running Internet Explorer 
    if (window.ActiveXObject) { 
     try { 
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
     } catch (e) { 
      xmlHttp = false; 
     } 
    } 
    // if running Mozilla or other browsers 
    else { 
     try { 
      xmlHttp = new XMLHttpRequest(); 
     } catch (e) { 
      xmlHttp = false; 
     } 
    } 
    // return the created object or display an error message 
    if (!xmlHttp) 
     alert("Error creating the XMLHttpRequest object."); 
    else 
     return xmlHttp; 
} 

Step 3.使用XMLHttpRequest對象

function process() { 
    // proceed only if the xmlHttp object isn't busy 
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) { 
     // retrieve the name typed by the user on the form 
     item = encodeURIComponent(document.getElementById("input_item").value); 
     // execute the your_file.php page from the server 
     xmlHttp.open("GET", "your_file.php?item=" + item, true); 
     // define the method to handle server responses 
     xmlHttp.onreadystatechange = handleServerResponse; 
     // make the server request 
     xmlHttp.send(null); 
    } 
} 

Step 4.執行的請奧波異步HTTP請求atically當從服務器

function handleServerResponse() { 

    // move forward only if the transaction has completed 
    if (xmlHttp.readyState == 4) { 
     // status of 200 indicates the transaction completed successfully 
     if (xmlHttp.status == 200) { 
      // extract the XML retrieved from the server 
      xmlResponse = xmlHttp.responseText; 
      document.getElementById("put_response").innerHTML = xmlResponse; 
      // restart sequence 
     } 
     // a HTTP status different than 200 signals an error 
     else { 
      alert("There was a problem accessing the server: " + xmlHttp.statusText); 
     } 
    } 
} 
71

收到消息,我知道這是一個相當古老的問題,但現在有在本地提供newer browsers一個更好的API。fetch()方法允許您發出Web請求。 例如,爲了從/get-data要求的一些JSON:

var opts = { 
    method: 'GET', 
    body: 'json', 
    headers: {} 
}; 
fetch('/get-data', opts).then(function (response) { 
    return response.json(); 
}) 
.then(function (body) { 
    //doSomething with body; 
}); 

詳情請參閱here

+6

實際上,聲稱Fetch API在「較新的瀏覽器」中工作是不正確的,因爲IE和Edge不支持它。 (邊緣14要求用戶專門啓用此功能)http://caniuse.com/#feat=fetch – saluce 2016-04-12 16:08:48

+4

這裏應該提到GitHub的polyfill。 https://github.com/github/fetch – TylerY86 2016-09-29 02:02:26

+6

只需添加''並使用像冠軍一樣的抓取。 – TylerY86 2016-09-29 02:05:15

11

老,但我會嘗試,也許有人會覺得這個信息有用。

這是您需要執行GET請求和獲取某些JSON格式化數據所需的最少量代碼。這僅適用於現代的瀏覽器,如最新版本的Chrome FFSafari瀏覽器歌劇院微軟邊緣

const xhr = new XMLHttpRequest(); 
xhr.open('GET', 'https://example.com/data.json'); // by default async 
xhr.responseType = 'json'; // in which format you expect the response to be 


xhr.onload = function() { 
    if(this.status == 200) {// onload called even on 404 etc so check the status 
    console.log(this.response); // No need for JSON.parse() 
    } 
}; 

xhr.onerror = function() { 
    // error 
}; 


xhr.send(); 

還檢查了新Fetch API這是一個基於承諾,替代XMLHttpRequest API

0

使用@Petah答案作爲一個巨大的幫助資源。我已經編寫了我自己的AJAX模塊,簡稱AJ:https://github.com/NightfallAlicorn/AJ並非所有的東西都經過了測試,但它適用於JSON的獲取和發佈。您可以隨意複製和使用源代碼。我還沒有看到明顯的接受答案,所以我認爲這是可以發佈。

26

這個版本在普通的情況下如何ES6/ES2015

function get(url) { 
    return new Promise((resolve, reject) => { 
    const req = new XMLHttpRequest(); 
    req.open('GET', url); 
    req.onload =() => req.status === 200 ? resolve(req.response) : reject(Error(req.statusText)); 
    req.onerror = (e) => reject(Error(`Network Error: ${e}`)); 
    req.send(); 
    }); 
} 

該函數返回promise。下面是關於如何使用功能和處理承諾它返回一個例子:

get('foo.txt') 
.then((data) => { 
    // Do stuff with data, if foo.txt was successfully loaded. 
}) 
.catch((err) => { 
    // Do stuff on error... 
}); 

如果需要加載,您可以使用JSON.parse()裝入的數據轉換成JS對象一個JSON文件。

您也可以將req.responseType='json'整合到函數中,但不幸的是有no IE support for it,所以我會堅持JSON.parse()

+2

使用'XMLHttpRequest'您可以異步嘗試加載文件。這意味着您的代碼將繼續執行,而您的文件將在後臺加載。爲了在腳本中使用文件的內容,您需要一種機制,在文件完成加載或加載失敗時告訴您的腳本。這就是*承諾*派上用場的地方。還有其他方法可以解決這個問題,但是我認爲* promises *是最方便的。 – Rotareti 2016-08-29 11:08:52

+0

@Rotareti移動瀏覽器是否支持這種方法? – bodruk 2017-01-24 16:19:17

+0

只有更新的瀏覽器版本支持它。通常的做法是在最新的ES6/7/..中編寫代碼,並使用Babel或類似方法將其轉換回ES5以獲得更好的瀏覽器支持。 – Rotareti 2017-01-24 17:34:56

2
var load_process = false; 
function ajaxCall(param, response) { 

if (load_process == true) { 
    return; 
} 
else 
{ 
    if (param.async == undefined) { 
    param.async = true; 
} 
if (param.async == false) { 
     load_process = true; 
    } 
var xhr; 

xhr = new XMLHttpRequest(); 

if (param.type != "GET") { 
    xhr.open(param.type, param.url, true); 

    if (param.processData != undefined && param.processData == false && param.contentType != undefined && param.contentType == false) { 
    } 
    else if (param.contentType != undefined || param.contentType == true) { 
     xhr.setRequestHeader('Content-Type', param.contentType); 
    } 
    else { 
     xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); 
    } 


} 
else { 
    xhr.open(param.type, param.url + "?" + obj_param(param.data)); 
} 

xhr.onprogress = function (loadTime) { 
    if (param.progress != undefined) { 
     param.progress({ loaded: loadTime.loaded }, "success"); 
    } 
} 
xhr.ontimeout = function() { 
    this.abort(); 
    param.success("timeout", "timeout"); 
    load_process = false; 
}; 

xhr.onerror = function() { 
    param.error(xhr.responseText, "error"); 
    load_process = false; 
}; 

xhr.onload = function() { 
    if (xhr.status === 200) { 
     if (param.dataType != undefined && param.dataType == "json") { 

      param.success(JSON.parse(xhr.responseText), "success"); 
     } 
     else { 
      param.success(JSON.stringify(xhr.responseText), "success"); 
     } 
    } 
    else if (xhr.status !== 200) { 
     param.error(xhr.responseText, "error"); 

    } 
    load_process = false; 
}; 
if (param.data != null || param.data != undefined) { 
    if (param.processData != undefined && param.processData == false && param.contentType != undefined && param.contentType == false) { 
      xhr.send(param.data); 

    } 
    else { 
      xhr.send(obj_param(param.data)); 

    } 
} 
else { 
     xhr.send(); 

} 
if (param.timeout != undefined) { 
    xhr.timeout = param.timeout; 
} 
else 
{ 
xhr.timeout = 20000; 
} 
this.abort = function (response) { 

    if (XMLHttpRequest != null) { 
     xhr.abort(); 
     load_process = false; 
     if (response != undefined) { 
      response({ status: "success" }); 
     } 
    } 

} 
} 
} 

function obj_param(obj) { 
var parts = []; 
for (var key in obj) { 
    if (obj.hasOwnProperty(key)) { 
     parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])); 
    } 
} 
return parts.join('&'); 
} 

我Ajax調用

var my_ajax_call=ajaxCall({ 
    url: url, 
    type: method, 
    data: {data:value}, 
    dataType: 'json', 
    async:false,//synchronous request. Default value is true 
    timeout:10000,//default timeout 20000 
    progress:function(loadTime,status) 
    { 
    console.log(loadTime); 
    }, 
    success: function (result, status) { 
     console.log(result); 
    }, 
     error :function(result,status) 
    { 
    console.log(result); 
    } 
     }); 

用於中止先前的請求

 my_ajax_call.abort(function(result){ 
     console.log(result); 
     }); 
5

youMightNotNeedJquery.com + JSON.stringify

var request = new XMLHttpRequest(); 
request.open('POST', '/my/url', true); 
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); 
request.send(JSON.stringify(data)); 
9

使用XMLHttpRequest

簡單的GET請求

httpRequest = new XMLHttpRequest() 
httpRequest.open('GET', 'http://www.example.org/some.file') 
httpRequest.send() 

簡單POST請求

httpRequest = new XMLHttpRequest() 
httpRequest.open('POST', 'http://www.example.org/some/endpoint') 
httpRequest.send('some data') 

我們可以指定該請求應該是異步的(真),默認情況下,或同步(假)與可選的第三個參數。

// Make a synchronous GET request 
httpRequest.open('GET', 'http://www.example.org/some.file', false) 

我們可以調用httpRequest.send()

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 

我們可以處理通過設置httpRequest.onreadystatechange給函數的響應之前設置頭調用httpRequest.send()

httpRequest.onreadystatechange = function(){ 
    // Process the server response here. 
    if (httpRequest.readyState === XMLHttpRequest.DONE) { 
    if (httpRequest.status === 200) { 
     alert(httpRequest.responseText); 
    } else { 
     alert('There was a problem with the request.'); 
    } 
    } 
} 
相關問題