2013-05-02 100 views
-1
<script> 
    try { 
     function xmldo() { 
      var xmlhttp; 
      xmlhttp = new XMLHttpRequest(); 
      xmlhttp.onreadystatechange = function() { 
       if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
        document.getElementById("para").innerHTML = xmlhttp.responseText; 
       } 
      } 
      var URL = "http:\\127.0.0.1\ajax.php"; 
      xmlhttp.open("GET", URL, true); 
      xmlhttp.send(); 
     } 
    } catch (err) { 
     document.write(err.message); 
    } 
</script> 
<p id="para">Hey message will change</p> 
<br> 
<button type="button" onclick="xmldo()">Click me</button> 

這是我的代碼的網頁我想我使用WAMP因此改變#para.innerHTML由respnse內容在我的另一個PHP文件ajax.php混淆基本的AJAX代碼

<?php 
$response="hey is text changed"; 
echo $response; 
?> 

我把我的ajax.php放在我的www文件夾中,並將服務器上的文件位置設置爲127.0.0.1/ajax.php [URL],但是我按下按鈕時,para佔位符處的文本沒有變化。 我是AJAX新手,所以在某些方面必須缺失。 Plz幫助他們。

+1

我會建議你使用一個庫如jQuery做AJAX請求 - 它的主要優點是,它需要更少的代碼,並在各種工作的瀏覽器。 – ajtrichards 2013-05-02 15:21:42

+0

您是否嘗試將'「http:\\ 127.0.0.1 \ ajax.php」'更改爲'「http://127.0.0.1/ajax.php」'? – Prusse 2013-05-02 15:22:54

+0

@ajtrichards我現在不知道Jquery,但非常感謝您寶貴的建議。 – 2013-05-02 15:30:06

回答

3

更改URL中的斜槓。

您有:http:\\127.0.0.1\ajax.php但正確的做法是:http://127.0.0.1/ajax.php

我也建議使用jQuery執行AJAX請求 - 這是更簡單,你寫更少的代碼!

我添加了一個例子下面寫的jQuery:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 

    $("#button_id").click(function(){ 

     $.ajax({ 
      url: 'http://127.0.0.1/ajax.php', 
      cache: false, 
      type: 'GET', 
      dataType: 'HTML', 
      error: function (e){ 
       console.log(e); 
      }, 
      success: function (response){ 
       $("#para").empty().append(response); 
      } 
     }); 

    }); 

}); 
</script> 

<p id="para">Hey message will change</p><br> 
<button type="button" id="button_id">Click me</button> 
+0

顯然成功:在最新的jQuery中已棄用(我實際上只是在這一天發現了這個!)它完成了:現在 – Dave 2013-05-02 15:30:03

+0

Oooh!我不知道那件事。謝謝@Dave – ajtrichards 2013-05-02 15:30:59

+0

Plz解決了我的問題,併爲我提供了正確的JavaScript代碼,目前我只知道它。並且該URL斜線不會對結果產生影響,但會改變它們 – 2013-05-02 15:31:39