2012-03-12 142 views
1

我有一個Ajax腳本,允許我在不刷新頁面的情況下檢查表單。但我希望它能檢查字段是否完整,但如果字段完整,我想將用戶發送到新頁面。使用Javascript/Ajax加載新頁面

我不知道我該如何做到這一點。下面是Ajax的腳本:

function pass() 
{ 

// Real Browsers (chrome) 

if (window.XMLHttpRequest) 
{ 
    xhr = new XMLHttpRequest(); 
} 

// IE 

else if (window.ActiveXObject) 
{ 
    xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
} 

//Store data 
var email = document.getElementById('email').value; 
var firstname = document.getElementById('firstname').value; 
var surname = document.getElementById('surname').value; 
var address1 = document.getElementById('address1').value; 
var address2 = document.getElementById('address2').value; 
var postcode = document.getElementById('postcode').value; 

//Open POST location 
xhr.open("POST","addUserSeminar.php"); 

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); 

//Make object to store all data 
var obj = {email: email, firstname: firstname, surname: surname, address1: address1, address2: address2, postcode: postcode}; 

//Encode the data with JSON and send it to the server 
xhr.send("data=" + JSON.stringify(obj)); 

//Check return state and change "myDiv" 
xhr.onreadystatechange=function() 
{ 

    if (xhr.readyState==4) 
    { 
     document.getElementById("settingsDiv").innerHTML = xhr.responseText; 
    } 

} 

//Return false so form doesn't submit 
return false; 
} 

它發送數據到一個PHP文件,其中我檢查框被填滿,如果「未找到名稱」像不是我的每一個消息。但是,如果所有數據都發布了,那麼我會向我的數據庫添加一條記錄,然後返回true。

我怎樣才能在我的Ajax腳本中獲取該返回值,以便我可以測試它的真實性,如果是這樣,則轉發到新頁面。

謝謝你的時間。

+0

嘗試使用'location.href = 「新位置的URL」 ' – 2012-03-12 15:08:09

+1

請保護你自己的靈魂,如果它不是絕對必要的,請不要自己創建XMLHttpRequest。使用[jQuery.ajax](http://api.jquery.com/jQuery.ajax/)或類似的東西... – Marc 2012-03-12 15:08:49

回答

0

返回字符串 「TRUE」 從服務器端成功

PHP代碼

if($valid_inputs) { // all input fields are valid 
    echo "TRUE"; 
} else { 
    echo "FALSE"; 
} 

客戶端JS代碼

if (xhr.readyState==4) 
{ 
    if (xhr.responseText.indexOf("TRUE") > -1) { 
     window.location = "redirecturl.php"; //redirect url 
    } 
} 
+0

這並不適合我。任何其他想法? – ragebunny 2012-03-12 15:48:44

+0

另外爲什麼> -1? – ragebunny 2012-03-12 15:49:48

+0

你能分享你的PHP代碼嗎? – Nemoy 2012-03-12 15:52:29

1

從服務器返回一些表明它已完成的內容,並使用if語句中的xhr.responseText讀取它。

if(xhr.responseText.indexOf("forward to next page") > -1){ 
    //forward 
} else { 
    //show error message 
} 

這將是好了很多,如果你使用JSON對象返回錯誤和成功消息,因爲你可以只檢查對象啥子做。

1

在你onreadystatechanged,readyState的== 4如果塊...

if(xhr.responseText.indexOf("SUCCESS") >= 0) { 
    window.location.href = NEW_URI; 
} else { 
    document.getElementById("settingsDiv").innerHTML = xhr.responseText; 
} 

讓你的PHP腳本返回一個唯一的字符串來表示VS成功與失敗是空白字段。