2012-08-05 119 views
0

我打電話給一個非常簡單的PHP頁面,但是調用總是返回任何內容,即使PHP很好。也就是說,您可以轉到PHP頁面的URL並看到它迴應「Hello World」,但當它使用JS調用時,它不會返回任何內容。Ajax調用PHP頁面總是返回任何內容,即使PHP頁面迴應什麼東西

下面是HTML頁面的JavaScript:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<title>Title of the document</title> 
</head> 

<body> 
The content of the document......<br /> 

Enter your email: <input id="email" type="text" /> 
<input type="button" onclick="setXMLHttpRequest()" value="Go!" /> 

<script type='text/javascript'/> 

     var http; 

     function setXMLHttpRequest() 
     { 
      if(window.XMLHttpRequest) 
       http = new XMLHttpRequest(); 
      else if(window.ActiveXObject) 
       http = new ActiveXObject("Microsoft.XMLHTTP"); 

       url = "http://www.convolutedconstruct.com /Ajax/checkemail.php?email=" + 
            document.getElementById('email').value; 
       http.onreadystatechange = display; 
       http.open("GET", url, true); 
       http.send(null); 

     } 

     function display() 
     { 
      if (http.readyState == 4) 
      { 
       infostr = http.responseText; 
       alert("From the PHP: " + infostr); 
      } 
     } 
</script></body></html> 

這裏是PHP頁面的內容 Click here for the live PHP page

<?php 
$email = $_GET['email']; 
echo "Hello World!"; 
?> 

爲什麼這回沒事了JS,即使PHP頁面正確地回顯文本?

+2

讓我猜猜,http://en.wikipedia.org/wiki/Same_origin_policy – Adi 2012-08-05 17:40:23

+0

@adnan說,這不是一個有效的路徑AJAX:'convolutedconstruct.com/Ajax/checkemail.php?email ='如果你想跨越原點試試JSONP – Sammaye 2012-08-05 17:41:46

+0

或者只是讓你的路徑:'/Ajax/checkemail.php?email =' – Sammaye 2012-08-05 17:42:13

回答

2

如上所示,AJAX請求通常只在調用者和被調用者位於同一個域時才起作用,您必須確保包含javascript的html代碼位於相同的域http://www.convolutedconstruct.com中。

如果不是,您可以使用CORS,讓你的Ajax通過在你的PHP輸出發送此頭從你的PHP頁面接收輸入的情況下

<?php 
header("Access-Control-Allow-Origin: *"); 
//rest of your code 
?> 

參見:http://enable-cors.org/

+0

我會將這兩個頁面放在服務器上的同一目錄中。在這種情況下,我應該使用相對路徑還是使用http前綴? – 2012-08-05 18:23:48

+1

他們不一定需要在相同的目錄,但如果這有助於您的方便,那麼是的,這是很好的。只要域和方案相同,就可以使用相對路徑或絕對路徑,該路徑也不會破壞ajax請求。因此,如果您的網頁位於http://www.example.com上,那麼它應該能夠從http://www.example.com上的任何頁面接收數據。我通常使用完整路徑 – 2012-08-05 18:25:40

1

我不喜歡使用XMLHTTP請求。相反,我使用jQuery的方法$.ajax({});方法。它總是適合我!

$.ajax({ 
    type: "POST", // or 'GET' 
    url: "your-url.php", // url that you are passing the data to 
    data: { 
     dataName: 'data to pass' // string, variable, object, array, etc 
    }, 
    success: function(output) { // output is what the url is 'echoing' back to the jQuery 
     // do something when the ajax method is complete. 
    } 
}); 

不要忘記導入jQuery的源代碼 - http://code.jquery.com/jquery-1.7.2.min.js

這些是最常見的是在使用AJAX組件。

如果您願意,我很樂意爲您提供更多幫助。

如果您想了解更多的只是檢查它的文檔:http://api.jquery.com/jQuery.ajax/