2013-06-24 143 views
1

我是新來的ajax,並且認爲我會成爲一個有趣的實驗放入我的項目。我創建了自己的燈箱類型功能,以在我創建的網站上發送消息。當用戶點擊「發送消息」時,這就是燈箱出現的時候,我試圖讓它說「發送消息給用戶」,其中用戶也是他們發送消息的用戶的名字。我的燈箱html元素實際上是在一個單獨的網頁上,這就是爲什麼我使用ajax。這是我到目前爲止,似乎並不能找出問題所在:Ajax通過url發送參數

user.php的頁面

<div id = "pageMiddle"> // This div is where all the main content is. 
    <button onclick = "showMessageBox(UsersName)">Send Message</button> 
</div> 

注:用戶名正確傳遞到JavaScript函數,我有檢查了很多。

main.js頁

function showMessageBox(user){ 
    alert(user); // where i checked if username passes correctly 
    var ajaxObject = null; 
    if (window.XMLHttpRequest){ 
    ajaxObject = new XMLHttpRequest(); 
    }else if (window.ActiveXObject){ 
    ajaxObject = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    if (ajaxObject != null){ 
    ajaxObject.open("GET", "message_form.php", true); 
    ajaxObject.send("u="+user); 
    }else{ 
    alert("You do not have a compatible browser"); 
    } 
    ajaxObject.onreadystatechange = function(){ 
    if (ajaxObject.readyState == 4 && ajaxObject.status == 200){ 
     document.getElementById("ajaxResult").innerHTML = ajaxObject.responseText; 
     // use jquery to fade out the background and fade in the message box 
     $("#pageMiddle").fadeTo("slow", 0.2); 
     $("#messageFormFG").fadeIn("slow"); 
    } 
    }; 
} 

message_form.php頁

<div id = "messageFormFG"> 
    <div class = "messageFormTitle">Sending message to <?php echo $_GET['u']; ?></div> 
</div> 

注:當直接通過URL訪問該頁面,給它的u參數的值,它正確顯示

回答

0

我看了一些ajax教程從bucky :)又名新波士頓後,我想出了它。如果我使用的是GET方法,我只需要將參數添加到.open函數中的url結尾,而不是通過send函數傳遞它(就像您使用post方法一樣)。

4

使用jQuery.ajax(); http://api.jquery.com/jQuery.ajax/

$.ajax({ 
    type: "GET", 
    url: "message_form.php", 
    data: { name: "John", location: "Boston" } 
}).done(function(msg) { 
    alert("Data Saved: " + msg); 
}); 
0

怪異的方式來做到這一點(老派):) 無論如何,我認爲這個問題可能是你正在加載整個HTML頁面的DIV!意義標籤和東西,理解錯誤的一個好方法是使用調試器並查看ajaxObject.responseText中的內容。

希望這會有所幫助。

順便說一句轉換爲jQuery ajax!節省你的時間加載=)

0

我相信你需要添加一個請求標題之前發送您的數據。所以你會有這樣的:

ajaxObject.open("GET", "message_form.php", true); 
ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
ajaxObject.send("u="+encodeURIComponent(user)); 

而不是你有什麼。

但是,讓圖書館爲你做這件事可能是個好主意。看起來你已經加載了jQuery,爲什麼不讓它處理你的AJAX請求呢?

+0

此使用jQuery Ajax庫當不需要。 – CarlosB

+0

這是正確的,CarlosB。這只是在不使用jQuery時才需要,因爲原始的海報正在做。我指出,在我解釋了在沒有jQuery的情況下處理請求的正確方法後,使用jQuery是一個好主意。 – CamHenlin

0

如果要使用ajax發送多個字段值,可以使用serilalize函數。

實施例:

jQuery.ajax({ 
     url: 'filenamehere.php', 
     type: 'post', 
     data: $("#formidhere").serialize(), 
     success: function(data){ 
    ..// 

     } 
    });