현재 jquery ajax에서 반환 데이터에 액세스 할 수 없습니다. 사실, 나는 데이터를 보내고 있는지 전혀 모른다. JSON을 사용하여 폼의 데이터를 PHP로 보내고 응답을 배열로 가져와야합니다.jQuery AJAX에서 PHP 응답을 처리하는 방법은 무엇입니까?
도움 주셔서 감사합니다.
HTML/JS/jQuery를
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<title>Hello World</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("form").submit(function() {
var uname = document.getElementById("username").value;
var pword = document.getElementById("password").value;
var postData = {
username: uname,
password: pword
};
alert(uname);
$.ajax({
url: "test.php",
type: "GET",
data: postData,
dataType: 'json',
contentType: 'json',
cache: false,
success: function (data) {
alert(data);
}
});
});
});
</script>
</head>
<body>
<form action="">
<input type='text' id="username" name="username" placeholder="Username" />
<br />
<input type='password' id="password" name="password" placeholder="password" />
<br />
<input type="submit" id="submit" value="Login" />
</form>
</body>
PHP
echo json_encode(array(
'username' => $_GET['username'],
'password' => $_GET['password']
));
알림에 표시되는 내용은 무엇입니까? JSON을 사용할 수있는 콘텐츠로 변환하려면 거기에'JSON.parse'를 사용해야 할 수도 있습니다. 그리고 Firebug와 같은 도구를 사용하여 보내고있는 것을 확인해 보았습니까? –
사실, 이제 약간의 수정 작업을 수행하고 응답을 다시 받는다는 것을 알았지 만 [object object]를 반환하고 있습니다. 배열을 JSON에서 JS로 다시 변환하려면 어떻게해야합니까? JSON.parse를 사용합니까? – copilot0910
@ copilot0910 :'JSON.parse (data);를 호출 할 필요가 있습니다. –