2014-10-09 50 views
-2

我有這段代碼調用buy.php並進行購買並顯示結果。Jquery獲取響應數據錯誤

store.php

<h4 class="result">Result:</h4> 
function buy(id) { 
     $.ajax({ 
      method: "GET", 
      URL: "buy.php?id="+id+"", 
      success: function (data) { 
       $(".result").html(data); 
      } 
     }); 


    } 

buy.php

(終於許多檢查後)

echo 'Purchase Successful!'; 

OR

echo 'Purchase Failed!'; 

store.php呼籲buy.php我得到

Jquery Makes a get request

這表明,jQuery的做使一個GET請求不buy.php,但網頁本身(store.php),當我撥打團購功能上當前頁面的重複內容。爲什麼它這樣做?任何幫助?

回答

2

ajax的URL選項是url,而不是URL。 JavaScript區分大小寫。

function buy(id) { 
    $.ajax({ 
     method: "GET", 
     url: "buy.php?id="+id+"", 
// Here^
     success: function (data) { 
      $(".result").html(data); 
     } 
    }); 
} 

附註:如果id是一個數字,你的代碼將工作,但有一個更好的方式來提供id值:使用data選項:

function buy(id) { 
    $.ajax({ 
     method: "GET", 
     url: "buy.php",    // <== change is here 
     data: {id: id},    // <== and here 
     success: function (data) { 
      $(".result").html(data); 
     } 
    }); 
} 

的好處關於使用data選項(與上面的對象一樣)是,jQuery將確保參數正確地進行URI編碼。再次,對於一個數字來說並不重要(如果id是一個數字),但是這是一個很好的習慣,因爲它對於字符串非常重要。

+2

發佈問題之前@AsheshKumar你需要一些R&d你的問題是很多時候問的問題,可能是downvote爲什麼 – 2014-10-09 09:48:38

+0

不好意思,說,但我不明白你的英語。 – 2014-10-09 09:50:10

+0

@AsheshKumar:基本上他在說:第一步是查看你正在使用的文檔和例子。在這種情況下,您可能已經看到它是「url」而不是「URL」。當然,如果你不知道JavaScript是區分大小寫的,你甚至可能沒有注意到這些文檔。 – 2014-10-09 09:53:18

0

嘗試改變URL網址和發送參數數據和文件的full url

function buy(id) { 
     $.ajax({ 
      method: "GET", 
      url: "http://localhost/html/home/buy.php",//change according file location 
      data:{'id':id}, 
      success: function (data) { 
       $(".result").html(data); 
      } 
     }); 
} 
+0

@AsheshKumar我不知道我不會downvote – 2014-10-09 09:44:24

0

選項方法嘗試的類型應該和你的URL必須是URL。

<h4 class="result">Result:</h4> 
function buy(id) { 
     $.ajax({ 
      type: "GET", 
      url: "buy.php?id="+id+"", 
      success: function (data) { 
       $(".result").html(data); 
      } 
     }); 


    }