将带有dataType:json的jQuery.ajax转换为纯javascript
Convert jQuery .ajax with dataType: json to plain javascript
我可以使用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);
相关文章:
- 将curl查询转换为jQuery.ajax()
- Ajax响应转换
- RoR-将提交表单转换为AJAX
- Ajax调用OGRE转换器
- javascript中是否有更标准化的方法来转换(序列化)非表单数据以与ajax一起使用
- 通过 ajax 将整数转换为字符串
- 将$.post转换为$.ajax
- 将带有dataType:json的jQuery.ajax转换为纯javascript
- 将dataUrl转换为blob并通过ajax提交
- 如何将AJAX POST转换为HTTP POST,以便在单击时发布
- 手图转换 C# Javascript/AJAX - 条形图
- 使用 ajax 时没有从文本到数组缓冲区的转换
- 使用Jquery将Ajax jsonp数据转换为数组
- 将通过Ajax(和Web Service方法)获得的数组转换为javascript数组
- 使用php解析xml并将其转换为json以与$.ajax一起使用时遇到问题
- 通过Ajax将对象数组(Javascript)转换为C#
- 我想在Iframe Javascript PHP的帮助下,将单个ajax上传器脚本转换为多个上传器
- 如何将日期选择器日期转换为JSON对象以用于AJAX请求
- 将curl转换为ajax请求
- 转换ajax查询字符串的成员