将带有dataType:json的jQuery.ajax转换为纯javascript

Convert jQuery .ajax with dataType: json to plain javascript

本文关键字:转换 ajax javascript jQuery dataType json      更新时间:2023-09-26

我可以使用jQuery进行快速绘图/原型设计,但我不能在我们的生产服务器上实现它。

我需要帮助,让以下的纯javascript版本发挥作用。在纯javascript版本中,submit.php没有接收json数据。

原始jQuery:

  $.ajax({
      type: "POST",
      url: "submit.php",
      data: json,
      dataType: "json",
      success: function(json){
        alert('success');
      }
  });

纯javascript:

  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.open("POST","submit.php",true);
  xmlhttp.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
  xmlhttp.send(json);
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {                 
      alert('success');
    }
  }

我找到了答案!!希望其他人觉得它有用。

jQuery添加默认标头(http://api.jquery.com/jquery.ajax/):

Content-Type: 'application/x-www-form-urlencoded; charset=UTF-8'
X-Requested-With: XMLHttpRequest

jQuery转换数据(http://api.jquery.com/jquery.ajax/):

"It is converted to a query string, if not already a string."

jQuery然后将请求作为常规POST查询字符串发送。

我在这里找到了从json转换为纯JavaScript POST查询字符串所需的片段:https://github.com/oyvindkinsey/easyXDM/issues/199

以下是更新后的纯JavaScript代码:

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.open("POST","submit.php",true);
xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    alert('success');
  }
}
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
var pairs = [];
for (var key in json) {
  pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(json[key]));
}
var data = pairs.join("&");
xmlhttp.send(data);