JSON:响应不过来
问题描述:
我希望有人能够帮助这一点,我有一个形式signup.php与AJAX是POST到另一个页面register.php。我无法从在register.php文件中调用的函数获得json响应。我将函数的结果编码在register.php文件中,但注册完成后没有任何内容显示出来。我在浏览器上设置了调试器以遵循网络响应,出于某种原因,头文件content-type是text/html,不知道是否是问题所在。JSON:响应不过来
我想要做的是在成功显示来自该功能的响应,但它不工作。这是我目前的代码。
signup.php
<script>
$(document).ready(function()
{
$("#submit").click(function()
{
var formData = $("#signup").serializeArray();
$.ajax(
{
type: "POST",
url: "../pages/register.php",
cache: false,
dataType: 'json',
data: formData,
success: function(response) {
$('#message').html(response);
}
});
return false;
});
});
</script>
<div data-role="page" data-theme="a">
<div data-role="header" data-position="inline">
<h1>Carelincs</h1>
</div>
<div data-role="content" data-theme="a">
<form action="" method="POST" id="signup">
<label for="email">Email:</label>
<input type="email" name="email" placeholder="eMail"/>
<br />
<label for="username">Username:</label>
<input type="text" name="username" placeholder="User Name"/>
<br />
<label for="password">Password:</label>
<input type="password" name="password" placeholder="Password"/>
<br />
<label for="confirm password">Confirm Password</label>
<input type="password" name="repeatpassword" placeholder="Confirm Password"/>
<br />
<button type="submit" id="submit">Submit</button>
</form>
<p id="message"></p>
<div data-role="popup" id="validate" class="">
<p>Account created! Activation email has been sent, check your email.</p>
</div>
</div>
</div>
register.php
<?php
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host=" . $config-> dbhost . ";dbname=" . $config->dbname, $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
$repeatpassword = $_POST["repeatpassword"];
$register = $auth->register($email, $username, $password, $repeatpassword);
// Temporary just so you can see what's going on :
echo json_encode($register);
?>
答
如果你要显示的数据,你必须访问该对象的字符串:
所以对于你的情况,你可以将标签更改为div
<div id="message"></div>
,然后分析在该专区
$('#message').html('<p> code: ' + response.code + '</p>');
$('#message').append('<p> message: ' + response.message+ '</p>');
+0
这个作品谢谢。 – Keez 2014-09-02 03:09:38
什么'response'包含JSON数据,你做了'的console.log (响应);'?如果它是一个对象,你不能在'.html()'中使用它。 – jeroen 2014-09-02 01:02:34
在输出你的JSON之前,尝试'header('Content-Type:application/json')',因为AJAX方法会显式地说你期待它,所以它会查找它:'dataType:'json','。 – 2014-09-02 01:02:47
同时检查AJAX调用中的“错误”。如果你的东西不能被翻译成JSON,jQuery会错误地调用该函数。 console.log()也是如此。 – Robbie 2014-09-02 01:27:59