2013-03-07 2 views
1

내 코드에 문제가 있습니다. 폼이 유효 할 때 변수를 포함 할 배열을 생성하여 폼의 유효성을 검사하고 싶습니다. 하지만 이렇게하려면 정보가 게시되었음을 알리기 위해 isset 메서드를 사용해야합니다. 다음은 간단한 예를isset으로 인해 getjson이 반환되지 않음

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를 만들 게시 된 경우 충분히 간단한


을합니다.

나는 JQuery와 양식이 양식을 제출하는 플러그인을 사용하고있어 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> 

를 얻기 위해 다음과 같은 방법을 사용하고 있습니다. {: 세계 이름 : 밥 안녕하세요}하지만 GET가 내 경고에서 무엇을 얻을이다 지정된에는 사용자 이름을 반환이

<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 반환을 보여줍니다처럼

은 내 양식을 보인다. 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'])) 같은 아마 뭔가 반환 고려할 수 있습니다 : 그것은 $_post

둘째 편집, $_POST 아니에요 기억,

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

편집 도를

귀하의 코드가 훨씬 더 될 것입니다 직관적이고 읽기 쉬운이 글 :

$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

+1

지금 약간의 수정을했습니다! 하지만 마지막 메모는 아마도 가장 중요합니다 ;-) – juco

+0

멋진데, 그래서 내가 업데이 트를했고 당신이 말했듯이, 나는 분명히 게시와 함께 보내지 않고 있다는 것을 의미하는 오류 사용자 명을 지정하지 않고있다. 내 질문은 왜 안되는거야. 내 콘솔의 네트워크 탭에 helloworld.php 메소드 게시가 명확하게 표시됩니다. 전송 된 것을 정확히 볼 수있는 방법을 알고 있습니까?미리보기는 또한 나에게 {hello : "world"name : "bob"} – richbai90

관련 문제