Ajax调用PHP失败,ASP正常工作.NET


Ajax call failing for PHP and working fine for ASP.NET

我正在做一个简单的Ajax调用,它在ASP中工作。NET,但是在onreadystatechange函数中放置断点时出现了一些奇怪的DOM异常。什么是额外的标题魔术ASP。NET正在做PHP没有做的事情,导致PHP的responseText为空,例如,当您在Google Chrome中查看xmlhttp变量时,只有DOM异常。

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) {
        //Here is where you unwrap the data
        var arr = UnWrapVars(xmlhttp.responseText);
        if (callBackFunc) {
            callBackFunc(arr);
        }
    }
};
xmlhttp.open("POST", ajaxURL, true);
if (navigator.userAgent.toLowerCase().indexOf('msie') == -1) {
    xmlhttp.overrideMimeType("application/octet-stream");
}
xmlhttp.send("[FunctionName]" + functionName + "[/FunctionName][CanvasID]" + canvasid + "[/CanvasID][WindowID]" + windowid.toString() + "[/WindowID][Vars]" + getEncodedVariables() + "[/Vars]");

来自Ajax页面的传入数据如下:[root][Vars][windows]

我是故意做[而不是<,所以请不要指出这一点,它在ASP.NET页面上工作,但在PHP页面上不工作。返回的数据与我在服务器端检查的数据相同。那么,如果任何ASP.NET做了PHP没有做的事,那么缺少的头魔法是什么呢?

这是因为$_POST实际上是访问通过表单发布的数据的简写。它需要合适的标头。将此行置于xmlhttp.send():之前

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

这将强制PHP填充$_POST数组。

或者,您可以创建一个Request实例,作为php://input流的自定义包装器。那么您的XHR调用将不需要发送额外的标头。