使用原生的ajax如何去提交json格式的数据

使用原生的ajax如何去提交json格式的数据

谢晋宇2272  |  浏览 346 次
发布于2016-11-16 22:52 最佳答案
function submit(){
var data={};
data.type=document.form.type.value;
data.comment=document.form.comment.value;

//get right XMLHttpRequest object for current browsrer
var x=ajaxFunction();

var string = JSON.stringify(data);

x.open('POST','echo.php',true);
x.setRequestHeader('Content-type','application/json; charset=utf-8');
x.setRequestHeader("Content-length", string.length);
x.setRequestHeader("Connection", "close");

x.onreadystatechange = function(){
if (x.readyState != 4) return;
if (x.status != 200 && x.status != 304) {
alert('HTTP error ' + req.status);
return;
}

data.resp = JSON.parse(x.responseText);
if(data.resp.status=='success'){
alert('That worked!');
}else{
alert('That didn\'t work!');
}
}
x.send(string);

return false; //prevent native form submit
}

你可能感兴趣的:(javascript)