2013-03-07 111 views
1

我遇到了我的代碼問題。我想通過在窗體有效時創建一個包含變量的數組來驗證我的窗體。但要做到這一點,我需要使用isset方法來知道信息已發佈。這裏有一個簡單的例子isset導致getjson返回undefined

http://richbaird.net/clregister

<?PHP 

if(isset($_POST['username'])) { 

$helloworld = array ("hello"=>"world","name"=>"bob"); 


print json_encode($helloworld); 

}; 

if(!isset($_POST['username'])) { 

echo json_encode(array('error' => true, 'message' => 'No username specified')); 



?> 


足夠簡單,如果用戶名已經公佈創建數組的HelloWorld。

我用下面的方法來獲取JSON

<script> 

//document ready 

$(document).ready(function(){ 

var php = "helloworld.php"; 

//submit form 
$("#loginform").ajaxForm 
(

//on successful submission 

function() { 

//getjson 

$.getJSON("helloworld.php",function(data) { 

    alert(data.message) 

}) //close get json 


.error(function(error) { alert(error.responsetext); }) 
.complete(function() { alert("complete"); }); 

} // close success 

) // close submit 




}); 
//end document ready 
</script> 

我使用jQuery插件的形式提交表單。

和我的形式看起來像這樣

<form id="loginform" name="loginform" method="post" action="helloworld.php"> 
<label for="username">username</label> 
<input type="text" name="username" id="username" /> 

<br /> 
<label for="password">password</label> 
<input name="password" type="password" /> 

<br /> 
<input name="submit" type="submit" value="Login" id="subtn" /> 

</form> 

網絡控制檯顯示POST方法返回{你好:世界名:鮑勃}但GET返回指定的任何用戶名這就是我在警報得到。它看起來像jquery試圖獲得代碼之前,它有一個機會完全處理,我怎樣才能防止這種情況?

回答

0

經過幾個小時的思考和juco的大量幫助,我意識到,我在這個函數中進行了2個獨立的調用。首先,我發佈了可以工作的數據,然後在一個成功的文章中,我試圖做出一個單獨的調用,一個GET請求,該請求包含應該提醒我結果的回調,但是因爲它使第二個調用,它發送一個GET請求變量POST永遠不會被設置,因此沒有東西可以回來。我修改了我的代碼,只使用post方法。

<script> 

//document ready 

$(document).ready(function(){ 





// bind form using ajaxForm 
$('#loginform').ajaxForm({ 
    // dataType identifies the expected content type of the server response 
    dataType: 'json', 

    // success identifies the function to invoke when the server response 
    // has been received 
    success: processJson 
} 





); 


function processJson(data) { 

alert(data.hello); 

} 




}); 
//end document ready 

1

你錯過了報價。應該是:

if(isset($_POST['username'])) 

您應該檢查您的控制檯,看看是否username實際上是越來越貼,因爲如果它不是,你不返回任何數據。你可以代替考慮返回錯誤if(!isset($_POST['username'])),或許是這樣的:

echo json_encode(array('error' => true, 'message' => 'No username specified')); 

編輯 另外,記住它的$_POST,不$_post

第二個編輯

您的代碼會更直觀易讀,如下所示:

$return = array(); 
if(isset($_POST['username'])) { 
    $return = array("hello"=>"world","name"=>"bob"); 
} else { 
    $return = array('error' => true, 'message' => 'No username specified'); 
} 
echo json_encode($return); 
+0

良好的漁獲,我加了引號,但仍然得到同樣的錯誤。查看編輯 – richbai90 2013-03-07 16:35:53

+1

我已經做了一些編輯!但最後一個音符可能是最重要的;-) – juco 2013-03-07 16:44:33

+0

酷,所以我做了更新,並按照你說的做,我得到的錯誤沒有指定用戶名,這顯然意味着它不會與郵件發送。我現在的問題是爲什麼不。我的控制檯的網絡標籤清楚地說明了helloworld.php方法後。你知不知道發送了什麼?預覽還給了我{你好:「世界」名稱:「鮑勃」} – richbai90 2013-03-07 16:56:28