jQuery替代jQuery.ajax() - 面临错误

时间:2015-07-14 14:06:17

标签: javascript php jquery json

这是input()

JS Object

以下AJAx请求正确传递数据

var datas = {
    name: "xyz",
    age:21,
}

var datas2 = JSON.stringify(datas);

开发者工具中的响应:

 $(function(){
        $.ajax({
            url:'two.php',
            type:'POST',
            dataType:'html',
            data:{data:datas2}
        });
    });

现在尝试使用 Javascript AJAX Reuest

Array
(
    [data] => {"name":"xyz","age":21}
)

开发者工具中的响应:

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.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {

    }
  }
xmlhttp.open("POST","two.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(datas2);

我哪里错了?

1 个答案:

答案 0 :(得分:2)

您正在发送两个不同的值。 jQuery会将对象data={"name":"xyz","age":21} 转换为字符串

xmlhttp.send(datas2)

{"name":"xyz","age":21} 只会发送字符串

{"name":"xyz","age":21}

这是一个很大的区别!在第二种情况下,xmlhttp.send('data=' + datas2') 被视为参数 name 而不是 value ,这是您在开发人员工具中看到的。

如果要发送相同的有效负载,则必须执行

        if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert(xmlhttp.responseText);
        }
    }
            xmlhttp.open("POST","file.jsp?latitude="+location.coords.latitude+"&longitude="+location.coords.longitude+"&accuracy="+location.coords.accuracy,true);                
            xmlhttp.send();
相关问题