将 json asnwer 放入 html 标记中

Put json asnwer into html tags

本文关键字:html 放入 json asnwer      更新时间:2023-09-26

我正在学习ajax,我面临着一个巨大的问题,我无法解决。我将一些变量发送到php中,在那里进行各种检查,然后将字符串值返回给ajax。我可以将它们显示在textare(奇怪的是结果立即消失)和输入字段中。我只想将它们显示在div s中。谁能解释一下我该怎么做,我将在下面留下一些注释代码。谢谢!P.S.这一切都是为了向用户显示注册表错误,也许我可以使用不同的方法?请随时提供一些建议。再次感谢!

PHP.php

<?php

 //various checking here
echo json_encode(array(
'email_error' => $email_error,
'password_error' =>$password));
?>

.html

<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>

<form>
Your email:
<input type = "text" id = "email"><br>
Your password:
<input type = "password" id = "password1"><br>
Repeat password:
<input type = "password" id = "password2"><br>
<button type = "submit" id = "push_button">PushMe</button>
</form>
<div id ="email_errors"> </div> <--I want to put variable $email_errors here -->
<div id = "password_errors"> </div> <--I want to put variable $password_errors here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type =                           "text/javascript" ></script>
<script type="text/javascript" src="java_script.js"></script>
</body>
</html>

java_script.js

$(document).ready(function ()   {
$('#push_button').click(function() {
$.ajax({
url: "php.php",
type: "POST",
dataType: "json", 
data: {
email: $("#email").val(),
password1: $("#password1").val(),
password2: $("#password2").val() 
},
success: function(data) {
$("#email_errors").val(data.email_error); // i return these values (i tried html data type either
$("#password_errors").val(data.password_error);
}
});
}); 
}) 

你只希望字符串变量显示在 Div 中?如果这就是你想要做的,你必须使用"html"而不是"val":

success: function(data) {
    $("#email_errors").html(data.email_error);
    $("#password_errors").html(data.password_error);
}

如果你的数据以 JSON 数据的形式返回,并且你想要显示整个对象,你可以执行以下操作:

success: function(data) {
    $("#email_errors").html(JSON.stringify(data));
}

另外:(我不知道它在 php 中的工作方式是否相同),您的$('#push_button').click()可能会生成回发,从而擦除div 内部 HTML。尝试将return false放在单击函数的末尾,以阻止回发:

$(document).ready(function () {

$('#push_button').click(function () {
    $.ajax({
        url: "php.php",
        type: "POST",
        dataType: "json",
        data: {
            email: $("#email").val(),
            password1: $("#password1").val(),
            password2: $("#password2").val()
        },
        success: function (data) {
            $("#email_errors").html(data.email_error); // i return these values (i tried html data type either
            $("#password_errors").html(data.password_error);
        }
    });
    return false; // this should stop the postback
});

})