簡體   English   中英

在ajax中將jquery轉換為純javascript

[英]convert jquery to pure javascript in ajax

我完全對 ajax 方法感到困惑。 我是 ajax ajaj(異步 javascript 和 json)的新手。 任何人都可以幫助我或提供任何想法如何在 javascript 中實現 ajax、GETajax、POSTajax,例如

$.ajax({
    method: "POST",
    url: "some.php",
    data: { name: "John", location: "Boston" }
}).done(function( msg ) {
     alert( "Data Saved: " + msg );
   }); // ajax


$.get( "ajax/test.html", function( data ) {
   $( ".result" ).html( data );
   alert( "Load was performed." );
 }); // getajax


$.post( "ajax/test.html", function( data ) {
   $( ".result" ).html( data );
}); //postajax

是的,您應該嘗試編寫自己的 ajax 函數。 不要從 jQuery 開始,從 var http_request = new XMLHttpRequest(); 開始;

把它放在一個函數中,添加功能......這是我的一個版本

<input type="button" onclick="button_click()" value="CLICK">
<div id="data"></div>
<script>
function button_click() {
  // example of use
  ajax({
    success: receiveNextLocations,
    url: 'ajax.php'
  });
  function receiveNextLocations(data) {
    document.getElementById('data').innerHTML = data;
  }
}

// ajax function that looks a bit like jQuery $.ajax
// minimal code for what I need; not dummy proof, no error handling ...
// feel free to extend this
var http_request = new XMLHttpRequest();
function ajax(options) {
  http_request.open(options.type || 'GET', options.url, true);
  http_request.send(options.data || null);
  http_request.onreadystatechange = function() {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        var type = options.dataType || '';
        switch (type.toLowerCase()) {
          default: 
            options.success(http_request.responseText);
            break;
          case 'json': 
            options.success(JSON.parse(http_request.responseText));
            break;
        }
      }
    }
  }
}
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM