dqoys62082
dqoys62082
2014-08-24 23:42

XMLHttpRequest没有返回值

  • xmlhttprequest
  • php
  • javascript

i am unable to receive a response from the php file.

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
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);

I have even tried to do this.....

 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

  <?php
    {
     $name = $_POST["film"];
      $file ='data_bollywood_romance.txt';
       $current=file_get_contents($file); //gets existing content from the file
    $current ="$current 
 $name 
";
   file_put_contents($file,$current); //put newstuff
    echo 'hi';
   return 'yes';
     }
   ?>

However this also does not seem to work... if i do alert("http.response") after http.send(params)...it alerts an alert with nothing written on it. I thought this might be because there is same origin policy problem so i tried to do Cross-domain Ajax with Cross-Origin Resource Sharing but that didnt work either( that is the second code). Thanks for your help in advance.

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐

换一换