2013-03-07 125 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