将jquery转换为ajax中的纯javascript [英] convert jquery to pure javascript in ajax

查看:72
本文介绍了将jquery转换为ajax中的纯javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对ajax方法感到困惑。我是ajax ajaj的新手(异步javascript和json)。任何人都可以帮助我或任何想法如何在javascript中实现ajax,GETajax,POSTajax

I am totally confused with ajax methods. I am new to ajax ajaj(asynchronous javascript and json). Can anyone help me or give any idea how to implement ajax, GETajax, POSTajax in javascript like

$.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()开始;

Yes, you should try writing an own ajax function. Don't start with jQuery, start with var http_request = new XMLHttpRequest();

将它放入函数中,添加功能...
这是我的一个版本

Put it in a function, add functionality ... Here is one of my versions

<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>

这篇关于将jquery转换为ajax中的纯javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆