2014-02-09 34 views
0

我正在構建一個使用Ajax檢索結果的搜索應用程序,但我在如何實現這個方面遇到了一些麻煩。這個jQuery Ajax/PHP設置有什麼問題?

我在Javascript以下代碼:

if (typeof tmpVariable == "object"){ 
    // tmpVariable is based on the query, it's an associative array 
    // ie: tmpVariable["apple"] = "something" or tmpVariable["orange"] = "something else" 
    var sendVariables = {}; 
    sendVariables = JSON.stringify(tmpVariable); 
    fetchData(sendVariables); 
} 

function fetchData(arg) { 
    $.ajaxSetup ({ 
     cache: false 
    }); 

    $.ajax ({ 
     type: "GET", 
     url: "script.php", 
     data: arg, 
    }); 
} 

並在的script.php

<?php 
    $data = json_decode(stripslashes($_GET['data'])); 
    foreach($data as $d){ 
     echo $d; 
    } 
?> 

它是什麼,我做錯了嗎?

謝謝。

+0

是真正的代碼?可能是'parse_str()'會起作用。 '$ data = parse_str(stripslashes($ _ GET ['data']),$ dataArray);'然後'foreach($ dataArray ['tmpVariable']爲$ d){echo $ d;}'。 – KeepMove

+0

@StevenWorks - 沒有,沒有改變任何東西。但是我認爲我已經將原因分離出來了,因爲當前頁面上的所有JavaScript都被破壞了,但是如果我註釋掉這個函數,那麼一切正常。 – user3262893

+0

什麼是JavaScript錯誤? – Sam

回答

1

您的PHP腳本需要一個名爲'data'的GET變量。用你的代碼你不會發送。

試試這個:

if (typeof tmpVariable == "object"){ 

    var data = {data : JSON.stringify(tmpVariable)}; // Added 'data' as object key 

    fetchData(data); 
} 

function fetchData(arg) { 

    $.ajax ({ 
     type: "GET", 
     url: "script.php", 
     data: arg, 
     success: function(response){ 

      alert(response); 

      $("body").html(response); // Write the response into the HTML body tag 
     } 
    }); 
} 
+0

好的,這看起來應該可以工作,但網頁上沒有任何迴應。我應該如何讓回聲出現?對不起,如果它是基本的,但我仍然試圖掌握Ajax的運作。 – user3262893

+0

是的,這不是它的工作原理。您正在將數據發送到PHP腳本'後臺',該腳本將通過回顯$ d(多次)'迴應'。但是除非你對這個迴應做了些什麼,否則你不會在瀏覽器中看到它。我會編輯我的答案,向你展示一個例子。同時,您是否有Firebug(Firefox)或網絡檢查員(Chrome等),以便您可以看到GET請求和響應? – JamesG

+0

這工作得非常好。你肯定幫助我更好地理解Ajax。謝謝! – user3262893