Javascript XMLHttpRequest无返回值
我无法收到来自php文件的响应 JavascriptJavascript XMLHttpRequest无返回值,javascript,php,xmlhttprequest,Javascript,Php,Xmlhttprequest,我无法收到来自php文件的响应 Javascript var http = new XMLHttpRequest(); var url = "http://localhost/php_bollywood_romance.php"; var params = "film="+movie_name_entered; http.open("POST", url, true); //Send the proper header information along with the request htt
var http = new XMLHttpRequest();
var url = "http://localhost/php_bollywood_romance.php";
var params = "film="+movie_name_entered;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
我甚至试过这样做
var http = new XMLHttpRequest();
if ("withCredentials" in http)
{
var url = "http://localhost/php_bollywood_romance.php";
var movie_name_entered="hi";
var params = "film="+movie_name_entered;
http.open("POST", url, true);
}
else if (typeof XDomainRequest != "undefined"){
http = new XDomainRequest();
var url = "http://localhost/php_bollywood_romance.php";
var movie_name_entered="hi";
var params = "film="+movie_name_entered;
http.open("POST", url);
} else {
http = null;
}
if (http){
http.onload = function(){
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
document.write(http.responseText);
callback(http.responseText);
alert("hey");
}
}
http.send(params);
};
PHP
然而,这似乎也不起作用。。。如果我在http.send(params)之后发出警报(“http.response”),它会发出警报,但上面没有写任何内容。我认为这可能是因为存在同源策略问题,所以我尝试使用跨源资源共享实现跨域Ajax,但这也不起作用(这是第二个代码)。提前感谢您的帮助。您不能设置这两个标题:
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
我试过了,但没试过,效果很好
就我个人而言,我会一直使用jQuery Ajax,但这只是“懒惰的我”:首先要检查浏览器开发人员控制台并查看请求的原始响应。首先,您需要确定您的PHP正在发送输出。我们如何知道PHP是否正在发送输出?我尝试了jQuery ajax,但这对我不起作用。我甚至删除了两个标题,但这不是很好,你需要做一些调试。。。打开Chrome javascript控制台,检查首次发出Ajax请求时抛出的错误。根据控制台告诉您的内容,您可能必须使用类似以下
标题(“Access-Control-allow-Origin:*”)的内容显式允许php脚本上的请求代码>顺便说一句:我只测试了第一个脚本,删除了有问题的标题。没有尝试你发布的第二个。
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");