2016-07-31 78 views

回答

0

這個怎麼樣?

var xmlhttp = new XMLHttpRequest(); 
xmlhttp.open("POST", "/your/url/here"); 
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); 
xmlhttp.send(
    JSON.stringify({f1:"v1", f2:123}) 
); 
0

官方網站W3School提供了大量的實例爲AJAX with Pure JS .

你可以檢查一下。無論如何,我喜歡將這個AJAX調用包裝在函數中,以便能夠將它重用於許多URL。

function simpleAjax(method,url,params,fnback){ 
      method=method || "GET"; 
      let xh=new XMLHttpRequest(); 
      with(xh){ 
       setRequestHeader("Content-Type", "application/json;charset=UTF-8"); 

        if(fnback){ // Async Call 
         open(method, url,true); 
         send(JSON.stringify(parmas)); 
         onreadystatechange= fnback.call(xh,xh.responseText) 
        }else{ //SYNC Call 
          open(method, url); 
          send(JSON.stringify(parmas)); 
          return xh; 
        } 


       } 

} 

然後,把它叫做:

  • 同步

    var request=simpleAjax('POST','/rest/my/url',{id:23}); 
    //console.log(request.responseText) ; 
    
  • 異步

    simpleAjax('POST','/rest/my/url',{id:23},function(response){ 
         console.log(response); 
        }) 
    
+1

*「官方網站W3School」* - 從哪個方面說它是「官方」?它與W3沒有任何關係。 – nnnnnn